382 words · 7 extracts anchored
`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.
C
#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):
12345size\_t fwrite(const void \*ptr, size\_t size, size\_t count, FILE \*file\_pointer);
****Parameters****
****Return Value****
This return value is generally used to check whether the write operation was successful or not.
The following examples demonstrate use of fwrite() function in C programs.
C
#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 successfullyA structure to a file can be written by fwrite() function as the raw binary data.
C
#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