C Library - fwrite() function



The C library fwrite() function writes data from the array pointed to, by ptr to the given stream.

Syntax

Following is the C library syntax of the fwrite() function −

size_t fwrite(const void *ptr, size_t size, size_t nmemb, FILE *stream);

Parameters

This function accepts the following parameters −

  • const void *ptr: Pointer to the array of elements to be written.

  • size_t size: Size in bytes of each element to be written.
  • size_t nmemb: Number of elements, each one with a size of size bytes.

  • FILE *stream: Pointer to the FILE object that identifies the stream where data will be written.

Return Value

The fwrite() function returns the total number of elements successfully written. If this number is less than nmemb, an error has occurred, or the end-of-file was reached.

Example 1

Writing an Array of Integers to a Binary File

This example writes an array of integers to a binary file named example1.bin. The output confirms that all 5 elements were successfully written to the file.

#include <stdio.h>

int main() {
   FILE *fp;
   int arr[] = {1, 2, 3, 4, 5};
   size_t n = sizeof(arr) / sizeof(arr[0]);

   fp = fopen("example1.bin", "wb");
   if (fp == NULL) {
      perror("Error opening file");
      return 1;
   }

   size_t written = fwrite(arr, sizeof(int), n, fp);
   printf("Number of elements written: %zu\n", written);

   fclose(fp);
   return 0;
}

Output

The above code produces following result −

Number of elements written: 5

Example 2

Writing a String to a Text File

This example writes a string to a text file named example3.txt. The output indicates that 13 characters (including the exclamation mark) were successfully written to the file.

#include <stdio.h>
#include <string.h>

int main() {
   FILE *fp;
   const char *str = "Hello, World!";

   fp = fopen("example3.txt", "w");
   if (fp == NULL) {
      perror("Error opening file");
      return 1;
   }

   size_t written = fwrite(str, sizeof(char), strlen(str), fp);
   printf("Number of elements written: %zu\n", written);

   fclose(fp);
   return 0;
}

Output

After execution of above code, we get the following result

Number of elements written: 13
Advertisements