A RetroSearch Logo

Home - News ( United States | United Kingdom | Italy | Germany ) - Football scores

Search Query:

Showing content from https://www.tutorialspoint.com/c_standard_library/c_function_fwrite.htm below:

C fwrite Function

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 −

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

RetroSearch is an open source project built by @garambo | Open a GitHub Issue

Search and Browse the WWW like it's 1997 | Search results from DuckDuckGo

HTML: 3.2 | Encoding: UTF-8 | Version: 0.7.4