Thursday, May 19, 2011

fread() example c c++ objc

Following code shows a fread() example code. fread() is used to read a block of data from a file. The file must be open with fopen() before calling fread() function. In most cases, fread() is used to read a binary file.[fread example]

Declaration.
size_t fread ( void * ptr, size_t size, size_t count, FILE * stream );

Parameters
ptr
Pointer to a block of memory with a minimum size of (size*count) bytes.
size
Size in bytes of each element to be read.
count
Number of elements, each one with a size of size bytes.
stream
Pointer to a FILE object that specifies an input stream.
 
fread example)
FILE                *infile, *outfile;
int                 width = 800, height=600;
char                buf[32];


// Prepare data for buf[32]
//  ... Your code here


// Create a binary file.
outfile = fopen("mytest.dat", "wb");


fwrite(&width, 4, 1, outfile);
fwrite(&height, 4, 1, outfile);
fwrite(buf, 1, 32, outfile);
fclose(outfile);


// Read the binary file created above.
infile = fopen("mytest.dat", "rb");
fread(&width, 4, 1, infile);
fread(&height, 4, 1, infile);
fread(buf, 1, 32, infile);
fclose(infile);