C++ fwrite()

fwrite() prototype

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

The fwrite() function writes count number of objects, each of size size bytes to the given output stream.

It is similar to calling fputc() size times to write each object. According to the number of characters written, the file position indicator is incremented. The resulting value of the file position indicator for the stream is indeterminate if any error occurs while reading the file.

  • If the objects are not trivially copyable, the behavior is undefined.
  • If the size or count is zero, a call to fwrite will return zero and no other action is performed.

It is defined in <cstdio> header file.

fwrite() Parameters

  • buffer: Pointer to the block of memory whose content is written.
  • size: Size of each objects in bytes.
  • count: The number of objects to read.
  • stream: The file stream to write the data to.

fwrite() Return value

The fwrite() function returns the number of objects read successfully. If an error occurs, the return value may be less than count.

Example 1: How fwrite() function works

#include <iostream>
#include <cstdio>

using namespace std;

int main()
{
    int retVal;
    FILE *fp;
    char buffer[] = "Writing to a file using fwrite.";

    fp = fopen("data.txt","w");
    retVal = fwrite(buffer,sizeof(buffer),1,fp);
    
    cout << "fwrite returned " << retVal;
    return 0;
}

When you run the program, the content of buffer will be written to the file and the output will be:

fwrite returned 1

Example 2: How fwrite() function works when either count or size is zero

#include <iostream>
#include <cstdio>

using namespace std;

int main()
{
    int retVal;
    FILE *fp;
    char buffer[] = "Writing to a file using fwrite.";

    fp = fopen("myfile.txt","w");
    
    retVal = fwrite(buffer,sizeof(buffer),0,fp);
    cout << "When count = 0, fwrite returned " << retVal << endl;
    
    retVal = fwrite(buffer,0,1,fp);
    cout << "When size = 0, fwrite returned " << retVal << endl;
    
    return 0;
}

When you run the program, the output will be:

When count = 0, fwrite returned 0
When size = 0, fwrite returned 0

Also Read:

Did you find this article helpful?