fwrite() is a standard library function used to write a block of data from memory to a file. It is mainly used for writing binary data, such as arrays and structures, directly into binary files.
- Writes one or more data elements to a file in binary format.
- Commonly used to store arrays, structures, and other blocks of data efficiently.
#include <stdio.h>
int main() {
FILE *fptr = fopen("gfg.bin", "wb");
int a[] = {1, 2, 3, 4, 5};
int n = sizeof(a) / sizeof(a[0]);
// Write array a[] into the file using fwrite
fwrite(a, sizeof(int), n, fptr);
fclose(fptr);
return 0;
}
The gfg.bin will contain the following data (in binary form):
12345Syntax
size_t fwrite(const void *ptr, size_t size, size_t count, FILE *file_pointer);
Parameters
- a: Name of the array to be written.
- size: Size of each element.
- count: Number of elements to be written.
- fptr: Pointer to the file.
Return Value
- It returns the number of objects written successfully.
This return value is generally used to check whether the write operation was successful or not.
Examples of fwrite()
The following examples demonstrate use of fwrite() function in C programs.
Writing a String to a Text File
#include <stdio.h>
#include <string.h>
int main() {
FILE *fptr = fopen("gfg.txt", "w");
// Create a string for write into the file
char s[] = "Hello, geeksforgeeks!";
// Wrtie the string into the file using fwrite
int n = fwrite(s, sizeof(char), strlen(s), fptr);
// Here we check whole file is written into file
if(strlen(s) == n){
printf("String written successfully");
}
fclose(fptr);
return 0;
}
Output
String written successfully
Writing a Structure to a File
A structure to a file can be written by fwrite() function as the raw binary data.
#include <stdio.h>
#include <string.h>
// Create a struct for inserting
typedef struct {
int a;
int b;
char s[20];
}GfG;
int main() {
FILE *fptr = fopen("gfg.bin", "wb");
GfG gfg = {1, 999, "GeeksforGeeks"};
// Wrtie the gfgHeader data into the file using fwrite.
int n = fwrite(&gfg, sizeof(gfg), 1, fptr);
// Check data written successfully.
if(n == 1){
printf("Structure written successfully");
}
fclose(fptr);
return 0;
}
Output
Structure written successfully