Structures & File I/O
Structures group related data into a single type. Combined with file I/O, you can persist structured data to disk. Structs are the foundation for data structures in C.
40 min•By Priygop Team•Last updated: Feb 2026
Struct & File Code
Example
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
// struct definition
typedef struct {
int id;
char name[50];
float gpa;
} Student;
// Enum
typedef enum { MON, TUE, WED, THU, FRI, SAT, SUN } Day;
// Union (shared memory)
typedef union {
int intVal;
float floatVal;
char strVal[20];
} DataValue; // Size = largest member (20 bytes)
// Function taking struct pointer (efficient — no copy)
void printStudent(const Student *s) {
printf("ID: %d, Name: %s, GPA: %.2f\n", s->id, s->name, s->gpa);
}
int main() {
// Create struct
Student alice = {1, "Alice Johnson", 3.85};
printStudent(&alice);
// Array of structs
Student class[3] = {
{1, "Alice", 3.85},
{2, "Bob", 3.42},
{3, "Charlie", 3.91}
};
// Dynamic struct allocation
Student *s = (Student *)malloc(sizeof(Student));
s->id = 4;
strcpy(s->name, "Diana");
s->gpa = 3.67;
free(s);
// File I/O: Text files
FILE *fp = fopen("students.txt", "w");
if (fp == NULL) { perror("Error"); return 1; }
for (int i = 0; i < 3; i++) {
fprintf(fp, "%d,%s,%.2f\n", class[i].id, class[i].name, class[i].gpa);
}
fclose(fp);
// Read text file
fp = fopen("students.txt", "r");
char line[100];
while (fgets(line, sizeof(line), fp)) {
printf("%s", line);
}
fclose(fp);
// Binary file I/O (faster, compact)
fp = fopen("students.bin", "wb");
fwrite(class, sizeof(Student), 3, fp);
fclose(fp);
Student loaded[3];
fp = fopen("students.bin", "rb");
fread(loaded, sizeof(Student), 3, fp);
fclose(fp);
return 0;
}