Open In App

How to Read a Struct from a Binary File in C?

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,

C Program to Read a Struct from a Binary File




// C program to read a struct from a binary file
#include <stdio.h>
  
typedef struct {
    int id;
    char name[50];
    float salary;
} Employee;
  
int main()
{
    // open the file in rb mode
    FILE* file = fopen("employee_data.bin", "rb");
  
    // check if the file was successfully opened
    if (file == NULL) {
        perror("Error opening file");
        return 1;
    }
  
    // Define the struct
    Employee employee;
  
    // Read the structs present in the file
    while (fread(&employee, sizeof(Employee), 1, file)
           == 1) {
        // Process the read data (e.g., print or manipulate)
        printf("Employee ID: %d, Name: %s, Salary: %.2f\n",
               employee.id, employee.name, employee.salary);
    }
    // close the file
    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)


Article Tags :