C Programming
Unions in C; Enumerations; File Handling in C
C-CAT
Unions in C
What is a Union?
A union is like a structure but all members share the same memory location. Only one member holds a value at a time — the size of a union = size of its largest member.
union data {
int i;
float f;
char str[20];
};
union data d;
d.i = 10;
printf("d.i = %d\n", d.i); // 10
d.f = 3.14; // Now f is active; i's value is overwritten!
printf("d.f = %.2f\n", d.f); // 3.14
printf("d.i = %d\n", d.i); // garbage (memory reused by f)
Struct vs Union
| Feature | Structure | Union |
|---|---|---|
| Memory | Sum of all member sizes | Size of largest member |
| Members active | All simultaneously | Only one at a time |
| Use case | Store multiple values | Store one of multiple types |
Use Cases for Union
// Network packet: either IPv4 or IPv6 address
typedef struct {
int is_ipv6;
union {
int ipv4; // 4 bytes
unsigned char ipv6[16]; // 16 bytes
} addr;
} ip_addr_t;
// Variant type (type-safe union)
typedef struct {
enum { INT, FLOAT, STRING } type;
union {
int i;
float f;
char s[20];
} value;
} variant_t;
Enumerations
What is an Enum?
An enum defines a set of named integer constants.
// Define enum
typedef enum {
MON = 1,
TUE, // 2 (auto-increment)
WED, // 3
THU, // 4
FRI, // 5
SAT, // 6
SUN // 7
} weekday_t;
// Usage
weekday_t today = WED;
printf("Day number: %d\n", today); // 3
// In switch
switch (today) {
case MON: case TUE: case WED: case THU: case FRI:
printf("Weekday\n");
break;
case SAT: case SUN:
printf("Weekend\n");
break;
}
Enum for Status Codes
typedef enum {
SUCCESS = 0,
ERR_NULL_POINTER = -1,
ERR_OUT_OF_MEMORY = -2,
ERR_FILE_NOT_FOUND = -3,
ERR_INVALID_INPUT = -4
} status_t;
status_t read_file(const char *filename) {
if (filename == NULL) return ERR_NULL_POINTER;
// ... read file ...
return SUCCESS;
}
File Handling in C
File Operations
#include <stdio.h>
// File modes:
// "r" - read text; file must exist
// "w" - write text; creates new /
overwrites
// "a" - append text; creates new / adds to end
// "rb" - read binary
// "wb" -
write binary
// "r+" - read+write; file must exist
// "w+" - read+write; creates new /
overwrites
int main() {
// Open file for writing
FILE *fp = fopen("data.txt", "w");
if (fp == NULL) {
printf("Error opening file!\n");
return 1;
}
// Write to file
fprintf(fp, "Name: Alice\n");
fprintf(fp, "Age: 25\n");
fprintf(fp, "Score: %.2f\n", 98.5);
// ALWAYS close file when done
fclose(fp);
// Open file for reading
fp = fopen("data.txt", "r");
if (fp == NULL) {
perror("fopen");
return 1;
}
// Read line by line
char line[100];
while (fgets(line, sizeof(line), fp) != NULL) {
printf("Read: %s", line);
}
fclose(fp);
return 0;
}
Reading and Writing Structures (Binary)
typedef struct {
int id;
char name[50];
float salary;
} employee_t;
void save_employee(const char *filename, employee_t *emp) {
FILE *fp = fopen(filename,
"wb"); // binary write
if (fp == NULL) { perror("fopen"); return; }
fwrite(emp, sizeof(employee_t), 1, fp); // write 1 record
fclose(fp);
}
void load_employee(const char *filename, employee_t *emp) {
FILE *fp = fopen(filename, "rb"); // binary read
if (fp == NULL) { perror("fopen"); return; }
fread(emp, sizeof(employee_t), 1, fp); // read 1 record
fclose(fp);
}
File Seek
FILE *fp = fopen("data.bin", "rb");
// Seek to specific position
fseek(fp, 0, SEEK_END); // Go to end of file
long
size = ftell(fp); // Get file size
fseek(fp, 0, SEEK_SET); // Go
back to beginning
// SEEK_SET: from beginning
// SEEK_CUR: from current position
// SEEK_END: from end
// Read record at specific index
int index = 2;
fseek(fp, index * sizeof(employee_t), SEEK_SET);
employee_t emp;
fread(&emp, sizeof(employee_t), 1, fp);
Continue learning
Related notes
Definition of AI; Need of AI
Artificial Intelligence
Introduction to Data Engineering; Big Data — The 5 V's; Types of Data
Big Data and Data Engineering
Introduction to C Programming; C Program Structure; Data Types and Variables
C Programming
What Is a Computer?; Machine Cycle: Fetch–Decode–Execute; CPU Organization
Computer Architecture
Put this topic into timed practice
Open mock tests when you want full-exam pacing, or keep drilling in practice mode.