Structures, Unions and File Handling in C For students.
A structure (struct) groups variables of different types under one name — e.g. a Student with name (text), roll number (integer) and marks (decimal). A union looks similar but stores all its members in the same memory, so only one member holds a valid value at a time. File handling is C's way of saving data permanently: opening files, reading and writing bytes, and closing them.
Structures matter because real entities are bundles of mixed data — a bank account or game character is never a single number. Unions matter in memory-tight systems needing only one alternative at a time. File handling matters because RAM forgets when the program ends; files are how programs remember.
Key Concepts
- struct definition: struct Student { char name[20]; int roll; float marks; }; declares a new type; struct Student s1 creates a variable of it.
- Member access: s1.roll = 7 via dot; for a pointer, ptr->roll via arrow.
- union: union Data { int i; float f; char str[10]; }; — all members share one memory block; writing to f destroys what was in i.
- struct vs union: struct size = sum of members (+ padding), union size = largest member; struct keeps everything, union one thing at a time.
- fopen modes: "r" read, "w" write (creates/truncates), "a" append, "r+"/"w+"/"a+" read+write; add "b" for binary.
- Core functions: fprintf/fscanf (formatted), fgetc/fputc, fgets/fputs, fread/fwrite (binary), fclose, fseek/ftell, feof.
How It Works
Writing "Hi" to a file, step by step:
- FILE *fp = fopen("note.txt", "w") asks the OS to create note.txt for writing; fp is the handle, NULL if it failed.
- fputc('H', fp) and fputc('B', fp)… — say fputc('H', fp) then fputc('i', fp) — place the bytes 'H' and 'i' into the file's buffer in order.
- fclose(fp) flushes the buffer to disk and releases the handle — skip it and the tail bytes may be lost.
- Later, fopen("note.txt", "r") plus fgetc reads the bytes back until EOF — the program "remembers" across runs.
Worked Example
Memory sizes (typical: 4-byte int, 4-byte float, 1-byte char):
struct S { char name[20]; int roll; float marks; };<br>union U { int i; float f; char s[10]; };
- struct S: name occupies bytes 0–19; roll needs 4-byte alignment and fits exactly at 20–23; marks at 24–27. Total = 28 bytes.
- union U: members share memory; size = largest member = char s[10] = 10 bytes.
- The struct keeps all three values for 28 bytes; the union keeps one valid value for 10 bytes — the classic space trade-off.
Common Misconceptions
- "struct and union are interchangeable." No — storing a float in a union member then reading it as an int gives reinterpreted garbage, not a conversion.
- "Writing to a file saves it instantly." Output is buffered; data reaches the disk on fclose or fflush — a crash before that loses the tail.
- "Text and binary modes are the same." On Windows, text mode translates newline characters; binary mode ("rb"/"wb") writes exact bytes — mandatory for images and data files.
Real-World Applications
- Databases: each table row is conceptually a struct, written to disk by the million.
- Operating systems: process tables, file descriptors and network packets are all structs.
- Embedded systems: unions map hardware registers where the same bytes mean different things in different modes.
- Games: save files serialise player structs; level data streams from files at load time.
Structures bundle mixed data into one unit, unions overlay alternatives in shared memory to save space, and file handling moves data from fleeting RAM to permanent disk — modelling real things, fitting tight memory, and surviving after the program ends.
Related blogs
- C Programming: Data Types, Operators and Control Statements
- Functions and Recursion in Programming With easy examples.
- Arrays and Strings: Complete Beginner's Guide For students.
- Pointers and Dynamic Memory: Complete Beginner's Guide
- Python Basics: Syntax, Lists, Dictionaries and Functions
- Object-Oriented Programming: Classes, Inheritance Guide.