Mail Archives: djgpp/1996/05/09/10:09:55
Reply to message 1888818 from THUNBERG AT ALGO on 05/06/96 5:40PM
>What is the appropriate way to read/write integers from/to a file with the
same
>size as it is stored in
>memory, i.e. a long integer (32bit) would occupy 4 bytes in the file. I have
>reached a solution but it seems
>rather clumsy:
Whoever taught you C obviously forgot to mention the fread() and fwrite()
functions for reading and writing binary data to files.
#define X 10
FILE *fp;
int n[X], m[X], i;
for ( i = 0; i < X; i++ )
scanf( "%d", n[i] );
fp = fopen( "foo.dat", "w+b" );
fwrite( n, sizeof(*n), X, fp );
fflush( fp );
rewind( fp );
if ( fread( &m, sizeof(*m), X, fp ) != X) /* returns # of items read */
printf( "Oops.\n" );
else
for ( i = 0; i < X; i++ )
printf( "%d ", m[i] );
fclose( fp );
- Raw text -