Thursday, May 19, 2011

fwrite() example c c++ objc

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

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

Parameters
ptr
Pointer to the array of elements to be written.
size
Size in bytes of each element to be written.
count
Number of elements, each one with a size of size bytes.
stream
Pointer to a FILE object that specifies an output stream.

fwrite 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);