/* ---------------------------------------------------------------------------- // Figure 15.16: Handling end-of-file and file input errors. // Handles end-of-file, hardware errors and format/data inconsistencies. // If using scanf, the eof test would be: if (feof( stdin )) ... // ---------------------------------------------------------------------------- */ #include "tools.h" #define in_name "feet2.in" #define log_name "feet2.log" void main( void ) { int data, flag; stream f_in = fopen( in_name, "r" ); stream f_log = fopen( log_name, "w" ); if (f_in == NULL) fatal( "Cannot open file %s for input.", in_name ); if (f_log == NULL) fatal( "Cannot open file %s for output.", log_name ); for (;;) { /* Main data processing loop. */ flag = fscanf( f_in, "%i", &data ); /* Read next item. */ if (flag == 1) { /* Test for successful read. */ printf( " Data: %i\n", data ); /* Process the data here. */ } else if (feof( f_in )) break; /* End of file -- leave loop. */ else if (ferror( f_in )) fatal( " Hardware error on input file." ); else { /* Flag error and do recovery.*/ fprintf( f_log, "\a Bad data: " ); clean_and_log( f_in, f_log ); /* Flush & echo rest of line. */ } } bye(); }