/* * ================================================================== * test_binary_io.c -- Demonstrate binary I/O operations with streams * ================================================================== * * Copyright (C) 1993-96 by Mark Austin and David Mazzoni. * * This software is provided "as is" without express or implied warranty. * Permission is granted to use this software on any computer system, * and to redistribute it freely, subject to the following restrictions: * * 1. The authors are not responsible for the consequences of use of * this software, even if they arise from defects in the software. * 2. The origin of this software must not be misrepresented, either * by explicit claim or by omission. * 3. Altered versions must be plainly marked as such, and must not * be misrepresented as being the original software. * 4. This notice is to remain intact. * * Written By: David Mazzoni June 1995 * ================================================================== */ #include #include /* define a simple little test structure */ typedef struct { char* cpName; int iToken; } data; int main( int argc, char* argv[] ) { FILE* FPbinary; data daVals[] = { { "First", 1 }, { "Second", 2 }}; /* define an array of struct data values */ int iIndex; if( argc < 2 ) { printf( "\nUsage: %s filename\n", argv[0] ); return -1; } /* [a] : Open the file for update in binary mode */ FPbinary = fopen( argv[1], "ab+" ); if( 0 == FPbinary ) { /* error on open */ printf( "\nError on opening %s. Exiting\n", argv[1] ); return -1; } /* [b] : Write out the data struct array */ fwrite( daVals, sizeof( daVals ) / sizeof( daVals[0] ), sizeof( daVals[0] ),FPbinary ); /* [c] : Now read them back in after flushing and seeking to the beginning */ fflush( FPbinary ); fseek( FPbinary, 0L, SEEK_SET ); fread( daVals, sizeof( daVals ) / sizeof( daVals[0] ), sizeof( daVals[0] ),FPbinary ); fclose( FPbinary ); /* [d] : Print the values read back from the file */ for( iIndex = 0; iIndex < sizeof( daVals ) / sizeof( daVals[0] ); ++iIndex ) printf( "Data value [%i]: %s , %i\n", iIndex, daVals[iIndex].cpName, daVals[iIndex].iToken ); return 0; }