For writing in the file, it is easy to write a string or an int to a file using fprintf and putc, but you might have faced difficulty when writing the contents of the struct. fwrite and fread make tasks easier when you want to write and read blocks of data.
In C language, structures are written/read in binary format, which ensures exact byte-by-byte storage and avoids issues like text formatting.
For writing/reading structures, the file should be opened in the binary mode ("rb", "wb" or "ab" ).
- rb: for binary reading
- wb: for binary writing
- ab: for appending binary
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.
Syntax of fwrite()
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.
Return Value: Number of objects written.
Example
#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
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.
Syntax of fread()
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.
Example
#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