/* fileio-3.c demonstrates the following: - FILE, fopen, fwrite, fread, fclose - writing and reading binary files of primitives - formatted console I/O of values read from binary files - #define - ferror() - returns a value that is re-initialized by each call to fwrite or fread. non zero value indicates I/O error - feof() returns true or false if EOF has been encountered on the stream just read Expects a command line arg: name of binary output file to be created Writes ten ints followed by ten doubles to that file then reopens the file fo reading, and echoes values to console */ #include #include #include #define NUM_INTS 10 #define NUM_DOUBLES 10 int main( int argc, char *argv[] ) { FILE *binaryFile; int i; /* loop counter as values are writen/read to/from file */ int iVal; /* a sequence of these will be written to outfile */ double dVal; /* folowed by a sequence of these */ if (argc < 2) { printf("usage: ./a.out \n"); exit(0); } /* OPEN FOR WRITE */ binaryFile = fopen( argv[1], "w" ); if (binaryFile == NULL) { fprintf(stderr,"Can't open binary output file %s\n", argv[1] ); exit(EXIT_FAILURE); } /* WRITE TEN INTS & TEN DOUBLES */ for (i=0 ; i<10 ; ++i) if ( fwrite( &i, sizeof(i), 1, binaryFile ) != 1) { if ( ferror(binaryFile) ) printf("I/O Err (fwrite)\n" ); else printf("???\n" ); exit(0); } for (dVal=0.0; dVal < 10.0 ; dVal += 1.0) if ( fwrite( &dVal, sizeof(dVal), 1, binaryFile ) != 1) { if ( ferror(binaryFile) ) printf("I/O Err (fwrite)\n" ); else printf("???\n" ); exit(0); } fclose( binaryFile ); /* RE-OPEN FOR READ BINARY. ECHO TO CONSOLE */ binaryFile = fopen( argv[1], "r" ); if (binaryFile == NULL) { printf("Can't open binary input file %s\n", argv[1] ); exit(0); } /* READ/ECHO TEN INTS & TEN DOUBLES */ for ( i=0 ; i<10 ; ++i ) if ( fread( &iVal, sizeof(iVal), 1, binaryFile) == 1 ) printf("%d ",iVal ); else { if ( ferror(binaryFile) ) printf("I/O Err (fread)\n" ); else if ( feof(binaryFile) ) printf("Premature EOF (fread)\n" ); else printf("???\n" ); exit(0); } printf("\n"); for ( i=0 ; i<10 ; ++i ) if ( fread( &dVal, sizeof(dVal), 1, binaryFile) == 1 ) printf("%f ",dVal ); else { if ( ferror(binaryFile) ) printf("I/O Err (fread)\n" ); else if ( feof(binaryFile) ) printf("Premature EOF (fread)\n" ); else printf("???\n" ); exit(0); } printf("\n"); fclose( binaryFile ); return EXIT_SUCCESS; } /* END MAIN */