Handle Structured Data When Reading and Writing Files in C

To handle structured data in C, you can use binary file operations with fwrite and fread, while or use fprintf and fscanf.


Example 1: Reading and Writing a Structure in Binary Mode

In this example, we will create a simple structure to store student information, write an instance of this structure to a binary file using fwrite, and then read it back using fread.

main.c

</>
Copy
#include <stdio.h>
#include <stdlib.h>

typedef struct {
    int id;
    char name[50];
    float grade;
} Student;

int main() {
    Student s1 = {101, "Alice", 88.5f};
    FILE *fp;

    // Write the structure to a binary file
    fp = fopen("student.dat", "wb");
    if (fp == NULL) {
        perror("Error opening file for writing");
        return EXIT_FAILURE;
    }
    fwrite(&s1, sizeof(Student), 1, fp);
    fclose(fp);

    // Read the structure from the binary file
    Student s2;
    fp = fopen("student.dat", "rb");
    if (fp == NULL) {
        perror("Error opening file for reading");
        return EXIT_FAILURE;
    }
    fread(&s2, sizeof(Student), 1, fp);
    fclose(fp);

    printf("ID: %d, Name: %s, Grade: %.2f\n", s2.id, s2.name, s2.grade);
    return 0;
}

Explanation:

  1. We define a structure Student with members id, name, and grade.
  2. An instance s1 is created and initialized with sample data.
  3. We open a file student.dat in binary write mode ("wb") and write the structure using fwrite.
  4. The file is then closed, and we reopen it in binary read mode ("rb").
  5. We read the data into another structure s2 using fread, and finally print the contents.

Output:

ID: 101, Name: Alice, Grade: 88.50

Example 2: Reading and Writing a Structure in Text Mode

In this example, we will use a similar structure to store employee details. We will write the structure data to a text file using fprintf and then read it back using fscanf.

main.c

</>
Copy
#include <stdio.h>
#include <stdlib.h>

typedef struct {
    int id;
    char name[50];
    double salary;
} Employee;

int main() {
    Employee e1 = {202, "Bob", 55000.75};
    FILE *fp;

    // Write the structure to a text file
    fp = fopen("employee.txt", "w");
    if (fp == NULL) {
        perror("Error opening file for writing");
        return EXIT_FAILURE;
    }
    fprintf(fp, "%d %s %lf\n", e1.id, e1.name, e1.salary);
    fclose(fp);

    // Read the structure from the text file
    Employee e2;
    fp = fopen("employee.txt", "r");
    if (fp == NULL) {
        perror("Error opening file for reading");
        return EXIT_FAILURE;
    }
    fscanf(fp, "%d %s %lf", &e2.id, e2.name, &e2.salary);
    fclose(fp);

    printf("ID: %d, Name: %s, Salary: %.2lf\n", e2.id, e2.name, e2.salary);
    return 0;
}

Explanation:

  1. We define an Employee structure containing id, name, and salary.
  2. An instance e1 is initialized with sample data.
  3. The file employee.txt is opened in write mode ("w"), and we write the employee data using fprintf in a formatted way.
  4. After closing the file, it is reopened in read mode ("r").
  5. Data is read back into another structure e2 using fscanf, and then printed.

Output:

ID: 202, Name: Bob, Salary: 55000.75

Conclusion

This tutorial demonstrated two different methods to handle structured data when reading and writing files in C. In the first example, we used binary file operations with fwrite and fread, while the second example showed text file operations using fprintf and fscanf.