Open In App

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

Last Updated : 22 Feb, 2024
Improve
Improve
Like Article
Like
Save
Share
Report

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




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



Like Article
Suggest improvement
Share your thoughts in the comments

Similar Reads