Previous Page
Next Page


Writes a number of objects of a given size to a file

#include <stdio.h>
size_t fwrite ( const void * restrict buffer , size_t size , size_t n ,
               FILE * restrict fp  );

The fwrite( ) function writes up to n data objects of the specified size from the buffer addressed by the pointer argument buffer to the file referenced by the FILE pointer fp. Furthermore, on systems that distinguish between text and binary file access modes, the file should be opened in binary mode.

The function returns the number of data objects that were actually written to the file. This value is 0 if either the object size size or the number of objects n was 0, and may be less than the argument n if a write error occurred.


typedef struct {
  char name[64];
  /* ... more structure members ... */
} item;

#define CACHESIZE 32                  // Size as a number of array elements.

FILE *fp;
int writecount = 0;
item itemcache[CACHESIZE];            // An array of "items".

/* ... Edit the items in the array ... */

if (( fp = fopen( "items.dat", "w" )) == NULL )
  perror ( "Opening data file" ), return -1;

/* Write up to CACHESIZE "item" records to the file.*/

writecount = fwrite( itemcache, sizeof (item), CACHESIZE, fp );

See Also

The corresponding input function, fread( ); the string output functions fputs( ) and fprintf( )

Previous Page
Next Page