/* Demonstration of error and EOF checking. Attempts to read integers from lst10-3.dat. Displays any line in error, and stops at EOF */ #include /* This contains the definition for the EOF macro */ #include FILE * file_open(char name[], char access_mode[]); main() { FILE * intfile; int intval, result; char buf[81]; /* Open file with file_open from lst10-2 (not repeated for brevity) */ intfile = file_open("lst10-3.dat", "r"); /* Read first value, remembering the fscanf result. */ result = fscanf(intfile, "%d", &intval); /* Loop as long as fscanf result is not EOF */ while (result != EOF) { /* But perhaps fscanf hit an error (a non-integer in the file). Input the troublemaker as a string, and display. */ if (result != 1) { /* Since correct input assigns value 1 */ /* Read the line as a string. */ fgets(buf, 81, intfile); /* Display error message. */ printf("fscanf result %d! Input was: \"%s\"\n", result, buf); } else { /* Fscanf must have worked - just print the integer. */ printf("fscanf result %d. Integer is %d\n", result, intval); } /* Input next value. */ result = fscanf(intfile, "%d", &intval); } /* After the loop, let's find out what value fscanf returned. */ printf("After last input, fscanf result was %d.\n", result); return 0; } FILE * file_open (char name[], char access_mode[]) { FILE * f; f = fopen (name, access_mode); if (f == NULL) { /* error? */ /* Library function perror prints an informative message. */ perror ("Cannot open file"); exit (1); /* Terminate after printing error message. */ } return f; /* Only happens if fopen succeeded. */ }