#### In C ##### Create a function that reads a text file with single digit value
ID: 3560919 • Letter: #
Question
#### In C #####
Create a function that reads a text file with single digit values seperated by commas. 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 original text file.
Conversion from the read character to an integer value can be done with the
following function:
int char_to_int(char c) {return c - '0';}
the function should be of the form:
int read(char* fileLocation, int numValues, int* values);
Explanation / Answer
#include<stdio.h>
int char_to_int(char c) {return c - '0';}
// function definition
int read(char* fileLocation, int numValues, int* values)
{
int i=0; // iterator for array
int array_full_eof_not_reached=0; // flag to mark that array full before eof
char ch; // variable for character input
FILE *fin = fopen(fileLocation,"r");
if(fin == NULL) return -3;
while(fscanf(fin,"%c,",&ch) != EOF)
{
printf("%c %d ",ch,i);
if(i<numValues)
values[i++]= char_to_int(ch);
else
{
array_full_eof_not_reached = 1;
break;
}
}
//printf("%d ",i);
if(i<numValues) return -1;
if(array_full_eof_not_reached == 1) return -2;
return 0;
}
// funtion ends
int main()
{
int arr[10];
printf("%d ",read("in.txt",5,arr));
return 0;
}
Related Questions
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.