/* fileio-2.c demonstrates: fread(), fwrite() array declaration and initilaization */ #include #include #include int main( int argc, char *argv[] ) { FILE *infile, *outfile; int x=7; unsigned int i; short h= 35; char c = 'Z'; int arr1[] = {3,5,7,11,13}; int arr2[5]; if (argc < 2 ) { printf("must enter a name for binary output file on cmd line\n"); exit( EXIT_FAILURE ); } outfile = fopen(argv[1], "wb" ); /* "wb" means we are writing binary to the file */ if (outfile==NULL) /* then the open must have failed */ { printf("Can't open %s for output.\n", argv[1] ); exit( EXIT_FAILURE ); } /* WRITE BINARY DATA TO THE FILE USING fwrite() */ printf("\nWriting to file %s\n", argv[1] ); fwrite( &x, sizeof(x), 1, outfile ); fwrite( &h, sizeof(h), 1, outfile ); fwrite( &c, sizeof(c), 1, outfile ); fwrite( arr1, sizeof(arr1), 1, outfile ); printf("...wrote %d %d %c ",x,h,c); for (i=0 ; i< sizeof(arr1)/sizeof(int) ; ++i) printf("%d ", arr1[i] ); printf("\n"); fclose( outfile ); /*RE-OPEN THAT FILE AS INPUT AND READ DATA BACK IN AND ECHO TO STDOUT */ infile = fopen(argv[1], "rb" ); /* "rb" means we are reading the binary file */ if (infile==NULL) /* we really don't expect this to happen considering we just wrote it - but we always test */ { printf("Can't open %s for input.\n", argv[1] ); exit( EXIT_FAILURE ); } printf("\nNow reading from file %s\n", argv[1] ); x=0; h=0; c=0; fread( &x, sizeof(x), 1, infile ); fread( &h, sizeof(h), 1, infile ); fread( &c, sizeof(c), 1, infile ); fread( arr2, sizeof(arr2), 1, infile ); fclose( infile ); printf("...read %d %d %c ",x,h,c); for (i=0 ; i< sizeof(arr1)/sizeof(int) ; ++i) printf("%d ", arr2[i] ); printf("\n"); return 0; }