fwrite() and fread() are standard C library functions used to write and read blocks of binary data. They are commonly used to store and retrieve structures directly from files without converting them to text.
- Structures are stored in binary format, preserving the exact memory layout and improving performance.
- The file should be opened in binary mode ("wb", "rb", or "ab") when using these functions.
Binary File Modes
- rb: Opens a file for binary reading.
- wb: Opens a file for binary writing (creates a new file or overwrites an existing one).
- ab: Opens a file for appending binary data at the end of the file.
#include <stdio.h>
struct Student {
int id;
char name[20];
float marks;
};
int main() {
struct Student s1 = {101, "Rahul", 89.5};
struct Student s2;
FILE *fp;
// Write structure to file
fp = fopen("student.dat", "wb");
fwrite(&s1, sizeof(struct Student), 1, fp);
fclose(fp);
// Read structure from file
fp = fopen("student.dat", "rb");
fread(&s2, sizeof(struct Student), 1, fp);
fclose(fp);
printf("ID: %d\n", s2.id);
printf("Name: %s\n", s2.name);
printf("Marks: %.1f\n", s2.marks);
return 0;
}
Output
ID: 101 Name: Rahul Marks: 89.5
Syntax
// Writing data
fwrite(ptr, size, count, file_pointer);
// Reading data
fread(ptr, size, count, file_pointer);
Parameters
- ptr: Pointer to the data to write/read.
- size: Size of each data element (usually sizeof(struct_name)).
- count: Number of elements to write/read.
- file_pointer: Pointer to the opened file.
Writing Structures to a File using fwrite
The first step for writing structures in a file is to open the file in "wb" or "ab" mode. Then, we can use the fwrite() function to easily write a structure to a file. The fwrite() function writes to the file stream in the form of a binary data block.
#include <stdio.h>
#include <stdlib.h>
// a struct to be read and written
struct person {
int id;
char fname[20];
char lname[20];
};
int main()
{
FILE* outfile;
// open file for writing
outfile = fopen("person.bin", "wb");
if (outfile == NULL) {
fprintf(stderr, "\nError opened file\n");
exit(1);
}
struct person input1 = { 1, "rohan", "sharma" };
// write struct to file
int flag = 0;
flag = fwrite(&input1, sizeof(struct person), 1,
outfile);
if (flag) {
printf("Contents of the structure written "
"successfully");
}
else
printf("Error Writing to File!");
// close file
fclose(outfile);
return 0;
}
Output
Contents of the structure written successfully
Syntax
size_t fwrite(const void *ptr, size_t size, size_t nmemb, FILE *stream)
Parameters
- ptr: pointer to the block of memory to be written.
- size: the size of each element to be written (in bytes).
- nmemb: number of elements.
- stream: FILE pointer to the output file stream.
Reading Structure from a File using fread
To read structure from a file we need to open the file in "rb" binary read mode and then we can simply read structures using fread() function. This function reads a block of memory from the given stream.
#include <stdio.h>
#include <stdlib.h>
// struct person with 3 fields
struct person {
int id;
char fname[20];
char lname[20];
};
int main()
{
FILE* infile;
// Open file for read + write
infile = fopen("person1.dat", "wb+");
if (infile == NULL) {
fprintf(stderr, "\nError opening file\n");
exit(1);
}
struct person people[] = {
{1, "Rohan", "Sharma"},
{2, "Amit", "Verma"},
{3, "Neha", "Singh"}
};
int count = sizeof(people) / sizeof(people[0]);
for (int i = 0; i < count; i++) {
fwrite(&people[i], sizeof(struct person), 1, infile);
}
struct person read_struct;
// Move file pointer to start
rewind(infile);
printf("Reading records:\n");
while (fread(&read_struct, sizeof(struct person), 1, infile) == 1) {
printf("ID: %d, Name: %s %s\n",
read_struct.id,
read_struct.fname,
read_struct.lname);
}
fclose(infile);
return 0;
}
Output
Reading records: ID: 1, Name: Rohan Sharma ID: 2, Name: Amit Verma ID: 3, Name: Neha Singh
Syntax
size_t fread(void *ptr, size_t size, size_t nmemb, FILE *stream)
Parameters
- ptr: pointer to the block of memory to read.
- size: the size of each element to read (in bytes).
- nmemb: number of elements.
- stream: FILE pointer to the input file stream.
Return Value: Number of objects read.