C fwrite() function

C library function - fwrite()

The fwrite() function is used to write up to count items, each of size bytes in length, from buffer to the output stream.


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

fwrite() Parameters:

Name Description Required /Optional
buffer A pointer to the data (to write out) or empty buffer (to read into). Required
size The size (number of bytes) of each element of data. Required
count The number of elements. Required
stream The opened (via fopen) stream. Required

Return value from fwrite()

  • Returns the number of full items successfully written, which can be fewer than count if an error occurs.
  • When using fwrite() for record output, set size to 1 and count to the length of the record to obtain the number of bytes written. You can only write one record at a time when using record I/O.

Example: fwrite() function

Following example write and read a specified string:

int main () {
   FILE *fp;
   char str[] = "C programming tutorial.";
   fp = fopen( "test.txt" , "w" );
   fwrite(str , 1 , sizeof(str) , fp );

   fp = fopen("test.txt","r");
   int c;
   while(1) {
      c = fgetc(fp);
      if( feof(fp) ) {
         break ;
      printf("%c", c);


C programming tutorial.

Errors: The value of errno can be set to:

Value Meaning
ECONVERT A pointer to the data (to write out) or empty buffer (to read into).
ENOTWRITE The file is not open for write operations.
EPAD Padding occurred on a write operation.
EPUTANDGET An illegal write operation occurred after a read operation.
ESTDERR stderr cannot be opened.
ESTDIN stdin cannot be opened.
ESTDOUT stdout cannot be opened.
ETRUNC Truncation occurred on I/O operation.
EIOERROR A non-recoverable I/O error occurred.
EIORECERR A recoverable I/O error occurred.

C Programming Code Editor:

Previous C Programming: C ftell()
Next C Programming: C remove()

Follow us on Facebook and Twitter for latest update.