here is some quick tutorial on file reading in c
/*
note to fopen(): file modes are defined usually by two character string
"rb" means open file for Read in Binary mode.
r=read w=write b=binary t=text so "wt" means open for Write in Text format
there are also other possibilites, but they are not used much ... they are mentioned in help :)
binary commands in simple are:
fread( pointer_to_data_buffer, 1, sizeof_data, file_handle );
fwrite( pointer_to_data_buffer, 1, sizeof_data, file_handle );
fread returns number of bytes read
fwrite returns number of bytes written
and text commands:
fprintf( file_handle, "text text text\n" );
fgets( buffer, buffer_size, file_handle );
fprintf prints formatted text to a file
fgets reads text from file until buffer_size bytes are read or end of line is read, which comes first.
*/
// Example 1
// This proggy will read 10 longs (4byte integers) from binary file
// and write them in human-readable form into text file
#include <stdio.h> // header for file functions
FILE *fin, *fout; // file handles
long i, l;
// input is in binary mode
fin = fopen( "somepath\\binary", "rb" );
// output will be in text mode
fout = fopen( "somepath\\text", "wt" );
// if fopen() fails then it returns NULL. So if you want to check if file
// was opened correctly then compare fin and fout to NULL
for( i=0; i<10; i++ ) {
fread( &l, 1, sizeof( long ), fin );
fprintf( fout, "Integer # %i. = %i\n", (int) i, (int) l );
}
fclose( fout );
fclose( fin );
//one more note
// to make things simplier when reading some complex structure, data can be read into structs too.
// maybe some byte-alignment pragma will be needed here for your compiler to pack the structure correctly without gaps between variables, if compiler's default variable alignment is 8bytes for example. #pragma pack (1) will do the trick for MSVC++
struct {
long length;
float coords[ 3 ];
} data;
fread( &data, 1, sizeof( data ), fin );