How to Read a Struct from a Binary File in C?
Last Updated :
22 Feb, 2024
The structure in C allows the users to create user-defined data types that can be used to group data items of different types into a single unit. We can save this structure in a file using C file handling. In this article, we will learn how we can read a struct from a binary file in C.
Read a Struct from a Binary File in C
To read a struct from a binary file in C, we will first have to open the binary file using the fopen() method in rb mode. Then we will use the fread() function to read the structure from the file.
Syntax of fread()
size_t fread(void * buffer, size_t size, size_t count, FILE * stream);
here,
- buffer: It refers to the pointer to the buffer memory block where the data read will be stored.
- size: It refers to the size of each element in bytes.
- count: It refers to the count of elements to be read.
- stream: It refers to the pointer to the file stream.
C Program to Read a Struct from a Binary File
C
#include <stdio.h>
typedef struct {
int id;
char name[50];
float salary;
} Employee;
int main()
{
FILE * file = fopen ( "employee_data.bin" , "rb" );
if (file == NULL) {
perror ( "Error opening file" );
return 1;
}
Employee employee;
while ( fread (&employee, sizeof (Employee), 1, file)
== 1) {
printf ( "Employee ID: %d, Name: %s, Salary: %.2f\n" ,
employee.id, employee.name, employee.salary);
}
fclose (file);
return 0;
}
|
Output
Employee ID: 1, Name: John Doe, Salary: 50000.0
Employee ID: 2, Name: Jane Smith, Salary: 60000.0
Time Complexity: O(N) where N is the number of structs in the file
Auxiliary Space: O(1)
Share your thoughts in the comments
Please Login to comment...