Header image  
AN OBSESSION IN COMPUTING  
line decor
  HOME  ::  
line decor
   
 
Binary File Functions
FILE *file_ptr = NULL; /* declare a file pointer variable */

Recommended way to open a file -
if ( (file_ptr = fopen("Filename.bin", "rb+")) == NULL )
{     printf("Error opening file\n");
      exit(1);
}

Reading from the file -
int fread ( void *ptr, size_t size, size_t num, FILE *stream);

Example of use -
fread( &float_val, sizeof(float_val), 1, file_ptr);
/* returns number of items read from file */

Writing to the file -
int fwrite( void *ptr, size_t size, size_t num, FILE *stream);

Example of use -
fwrite( &float_val, sizeof(float_val), 1, file_ptr);
/* returns number of items written to file */

Moving the file pointer ( random access of the file) -
fseek( FILE *stream, long offset, int origin);
Where origin will be one of the following -
SEEK_SET = Start of file.
SEEK_CUR = Current position in file.
SEEK_END = End of file.

Example of use -
fseek( file_ptr, (long)-1 * sizeof(int), SEEK_CUR);
Example will move the file pointer back one int, i.e. read/write the previous integer stored in the file.

Report current file pointer position -
long ftell( FILE *stream ); /* returns -1 when an error occurs */

Reset file pointer back to the start of the file -
void rewind ( FILE *stream );
/* resets EOF and error flags in the process */

Closing the file after use -
fclose( FILE *stream );

Example of use -
fclose (file_ptr);
stream = NULL;

 
       

© Copyright 1999-2008 @incubus. All Rights Reserved. All trademarks acknowledged.
incubus.co.uk || zenithpaints.co.uk || rankinstine.co.uk