📁📚Intermediate

Read/Write Structure to a File

Structure file operations

Read and write structures to a file using binary mode.

Program Code

struct_file.c
C
1#include <stdio.h>
2
3struct Student {
4 int id;
5 char name[50];
6 float gpa;
7};
8
9int main() {
10 struct Student students[] = {
11 {101, "Alice", 3.9},
12 {102, "Bob", 3.7},
13 {103, "Charlie", 3.5}
14 };
15 int n = 3;
16
17 // Write to binary file
18 FILE *fp = fopen("students.dat", "wb");
19 if (fp == NULL) {
20 printf("Error opening file!\n");
21 return 1;
22 }
23
24 fwrite(students, sizeof(struct Student), n, fp);
25 fclose(fp);
26 printf("Data written to students.dat\n\n");
27
28 // Read from binary file
29 struct Student readStudents[3];
30
31 fp = fopen("students.dat", "rb");
32 if (fp == NULL) {
33 printf("Error opening file!\n");
34 return 1;
35 }
36
37 fread(readStudents, sizeof(struct Student), n, fp);
38 fclose(fp);
39
40 printf("Data read from file:\n");
41 for (int i = 0; i < n; i++) {
42 printf("ID: %d, Name: %s, GPA: %.2f\n",
43 readStudents[i].id,
44 readStudents[i].name,
45 readStudents[i].gpa);
46 }
47
48 return 0;
49}
Output

Data written to students.dat

 

Data read from file:

ID: 101, Name: Alice, GPA: 3.90

ID: 102, Name: Bob, GPA: 3.70

ID: 103, Name: Charlie, GPA: 3.50

Want to Learn More?

Explore our comprehensive tutorials for in-depth explanations of C programming concepts.

Browse Tutorials
Back to All Examples