This example program reads a file line by line checking the content. It has minimal error feedback, which could be more informative.
#include <stdio.h>
int main (void)
{
FILE *inputFile = fopen("test.txt", "rt");
if(inputFile == NULL) {
return 1; // file failed to open
}
char buf[100];
// first line
if(fgets(buf, sizeof buf, inputFile) == NULL) {
return 1; // could not read first line
}
if(buf[0] != 'R') {
return 1; // first line data was invalid
}
// data lines
while(fgets(buf, sizeof buf, inputFile) != NULL) {
int val;
if(sscanf(buf, "%d", &val) != 1) { // was the conversion successful?
break;
}
printf("%d\n", val);
}
// check last line was valid
if(buf[0] != 'W') {
return 1; // last line data was invalid
}
puts("Success");
return 0;
}
Input file
R
+1
-5
W
Program output
1
-5
Success
For simplicity, the program ignores closing the file. The idea is to show how to control the file reading.