Standard Library Functions in C

adplus-dvertising
fwrite() Function
Previous Home Next

Description

The C library function, The fwrite() function writes up to count items, of size length each, from buffer to the output stream. The file pointer associated with stream (if there is one) is incremented by the number of bytes actually written.

Declaration

Following is the declaration for fwrite() function.

size_t fwrite( const void *buffer, size_t size, size_t count, FILE *stream );

Parameters

buffer - Pointer to the array of elements to be written, converted to a const void*.

size - This is the size in bytes of each element to be written

count - Number of elements, each one with a size of size bytes. size_t is an unsigned integral type.

stream- The stream to write to.

Return Value

The fwrite function returns the number of full items actually written, which may be less than count if an error occurs. Also, if an error occurs, the file-position indicator cannot be determined.

Example

#include <stdio.h>
#include <stdlib.h>
int main(void)
{
FILE *fp;
double d = 12.23;
int i = 101;
long l = 123023L;
if((fp=fopen("test", "wb+"))==NULL) {
printf("Cannot open file.\n");
exit(1);
}
fwrite(&d, sizeof(double), 1, fp);
fwrite(&i, sizeof(int), 1, fp);
fwrite(&l, sizeof(long), 1, fp);
rewind(fp);
fread(&d, sizeof(double), 1, fp);
fread(&i, sizeof(int), 1, fp);
fread(&l, sizeof(long), 1, fp);
printf("%f %d %ld", d, i, l);
fclose(fp);
return 0;
}

Output

Cannot open file.
Previous Home Next