Academic Integrity: tutoring, explanations, and feedback — we don’t complete graded work or submit on a student’s behalf.

C language 3. Write a function to read in values from a CSV text file (1 mark) W

ID: 3560781 • Letter: C

Question

C language

3. Write a function to read in values from a CSV text file (1 mark) Write a function that reads in a single line CSV (comma separated values) text file. The file is expected to be a plaintext *.txt file with single digit integer values separated by commas. You should abide by the following: ? The return value should be -1 if the EOF was reached before the array was filled, -2 if the EOF was not reached before the array was filled, -3 if opening the file failed, or 0 otherwise. ? values should point to a pre-allocated array with a length of numValues. At the completion of this function, values should contain the values from the CSV file. ? You can assume: There are no empty values in the CSV Each value is only a single character (i.e. digit) Conversion from the read character to an integer value can be done with the following function: int char_to_int(char c) return c-'o': Use the follwoing function signature for your solution: int read_basic _csv(char*fileLocation, int numValues, int*values);

Explanation / Answer

#include<stdio.h>
int char_to_int(char c)
{
return c-'0';
}
int read_basic_csv(char* fileLocation,int numValues,int* values)

{
    FILE* fp= fopen(fileLocation, "r");
    getchar();
   int i;
   char c,d;
   // unable to open file return -3;
   if(!fp)
   return -3;
   for(i=0; i<numValues; i++)
   {
    // if end of file reached before array filled return -1;
   if(feof(fp))
   return -1;
   fscanf(fp,"%c%c",&c,&d);
   values[i] = char_to_int(c);
   }
   // array filled but more numbers are there return -2
   if(!feof(fp))
   return -2;
   // none of the above return 0;
   return 0;
}
int main()
{
int values[10];
int success_value = 0;
int numValues = 10;
char filename[100];
int i;
printf("Enter file name to read list of integers :");
scanf("%s",filename);
success_value = read_basic_csv(filename, numValues, values);
//for(i=0; i<numValues; i++)
//printf("%3d",values[i]);
printf("Return value is %d",success_value);
return 0;
}