Structs and Files
Structs and File I/O in C
struct definition Groups related variables of different types under one name:
c
struct Point { int x; int y; };
struct Point p = {3, 4};Use typedef to avoid repeating struct:
c
typedef struct { int x; int y; } Point;
Point p = {3, 4};Struct pointers with ->
When you have a pointer to a struct, use -> to access members (equivalent to (*ptr).member):
c
Point *pp = &p;
printf("%d\n", pp->x);File I/O
fopen(path, mode)— opens a file ("r","w","a","rb", etc.)fclose(fp)— closes the file and flushes the bufferfprintf(fp, fmt, …)— writes formatted textfscanf(fp, fmt, …)— reads formatted textfgets(buf, size, fp)— reads a line safely- Always check
fopenreturns non-NULL
Key points:
- Structs are value types — assignment copies all fields.
- File handles (
FILE*) must be closed to avoid resource leaks. - Prefer
fgetsoverfscanffor reading strings to avoid buffer overflows.
Code Examples
typedef struct and pointer accessc
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
typedef struct {
char name[50];
int age;
double gpa;
} Student;
void printStudent(const Student *s) {
printf("Name: %s, Age: %d, GPA: %.2f\n", s->name, s->age, s->gpa);
}
int main(void) {
Student s1;
strncpy(s1.name, "Alice", sizeof(s1.name) - 1);
s1.name[sizeof(s1.name) - 1] = '\0';
s1.age = 20;
s1.gpa = 3.85;
printStudent(&s1);
Student *s2 = (Student*) malloc(sizeof(Student));
strncpy(s2->name, "Bob", sizeof(s2->name) - 1);
s2->name[sizeof(s2->name) - 1] = '\0';
s2->age = 22;
s2->gpa = 3.5;
printStudent(s2);
free(s2);
return 0;
}The dot operator accesses struct members by value; -> accesses them through a pointer. Both s1 and s2 use the same printStudent function.
File I/O with fprintf and fgetsc
#include <stdio.h>
#include <string.h>
int main(void) {
// Write to a file
FILE *fp = fopen("students.txt", "w");
if (fp == NULL) {
fprintf(stderr, "Cannot open file\n");
return 1;
}
fprintf(fp, "Alice 20 3.85\n");
fprintf(fp, "Bob 22 3.50\n");
fprintf(fp, "Charlie 21 3.70\n");
fclose(fp);
// Read back
fp = fopen("students.txt", "r");
if (fp == NULL) return 1;
char name[50];
int age;
double gpa;
while (fscanf(fp, "%s %d %lf", name, &age, &gpa) == 3) {
printf("%-10s age=%d gpa=%.2f\n", name, age, gpa);
}
fclose(fp);
return 0;
}fopen returns NULL on failure — always check. fscanf returns the number of items matched; the loop exits when it can no longer match 3 items.
Quick Quiz
1. What is the difference between `.` and `->` for struct member access?
2. What does `fopen` return if it fails to open a file?
Was this lesson helpful?