ftp.delorie.com/archives/browse.cgi   search  
Mail Archives: djgpp/1996/05/09/10:09:55

From: j DOT aldrich6 AT genie DOT com
Message-Id: <199605091349.AA117369770@relay1.geis.com>
Date: Thu, 9 May 96 13:41:00 UTC 0000
To: djgpp AT delorie DOT com
Mime-Version: 1.0
Subject: Re: i/o file handling - intege

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 -


  webmaster     delorie software   privacy  
  Copyright © 2019   by DJ Delorie     Updated Jul 2019