C++ Standard Library C++ STL Library

C++ <cstdio> - fwrite() Function



The C++ <cstdio> fwrite() function writes up to count elements, each one with a size of size bytes, from the block of memory pointed by buffer to the current position in the stream. The file position indicator of the stream is advanced by the number of characters written.

Syntax

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

Parameters

buffer Specify pointer to the array of elements to be written, converted to a const void*.
size Specify size, in bytes, of each element to be written.
size_t is an unsigned integral type.
count Specify number of elements, each one with a size of size bytes.
size_t is an unsigned integral type.
stream Specify a pointer to a FILE object that specifies an output stream.

Return Value

Returns the total number of elements successfully written. It may be less than count if a writing error occurs. In this case, the error indicator ferror() is set for the stream.

If size or count is zero, fwrite() returns zero and performs no other action.

Example: fwrite() example

In the example below the fwrite() function is used to write some content to a text file then fread() function is used to read the content of this file.

#include <cstdio>
#include <cstring>

int main (){
  char c[] = "Hello World!";
  char buffer [100];

  //open the file in write and read mode
  FILE *pFile = fopen("test.txt", "w+");

  //write data to the file
  fwrite(c, strlen(c) + 1, 1, pFile);

  //seek to the beginning of the file
  fseek(pFile, 0, SEEK_SET);

  //read and display data
  fread(buffer, strlen(c)+1, 1, pFile);
  printf("%s\n", buffer);
  
  //close the file
  fclose(pFile);

  return 0;
}

The output of the above code will be:

Hello World!

Example: Writing to a file using append mode

Lets assume that we have a file called test.txt. This file contains following content:

This is a test file.
It contains dummy content.

In the example below, the fwrite() function is used to append some content to the end of the file.

#include <cstdio>
#include <cstdlib>
#include <cstring>

int main (){
  char c[] = "\nThird line is added.";
  long lSize;
  char * buffer;

  //open the file in read mode
  FILE *pFile = fopen("test.txt", "a+");

  //write data to the file
  fwrite(c, strlen(c) + 1, 1, pFile);

  //obtain file size
  lSize = ftell (pFile);
  rewind (pFile);

  //allocate memory to buffer to contain the whole file
  buffer = (char*) malloc (sizeof(char)*lSize);  
  
  //read and display the whole file
  fread(buffer, 1, lSize, pFile);
  printf("%s", buffer);
  
  //close the file
  fclose(pFile);

  return 0;
}

The output of the above code will be:

This is a test file.
It contains dummy content.
Third line is added.

❮ C++ <cstdio> Library