FILE *file_ptr = NULL;
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);
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);
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 );
Reset file pointer back to the start of the file -
void rewind ( FILE *stream );
Closing the file after use -
fclose( FILE *stream );
Example of use -
fclose (file_ptr);
stream = NULL; |