fwrite() in C (original) (raw)

Last Updated : 8 Jan, 2025

In C, **fwrite() is a built-in function used to write a block of data from the program into a file. It can write arrays, structs, or other data to files but is especially designed to write binary data in binary files.

**Example:

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):

12345

**Explanation: In the given program, **fwrite() writes the integer array **a[] as raw binary data to the file **gfg.bin. It writes **n elements of size **sizeof(int) from the array **a to the file.

This article covers the syntax, uses and common examples of fwrite() functions in C.

Table of Content

Syntax of fwrite()

fwrite() is a standard library function defined in ****<stdio.h>** header file in C.

**fwrite(a, size, count, fptr);

**Parameters:

**Return Value:

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

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 successfully

Writing a Structure to a File

A 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