Structures, Unions, and File Handling in C – Complete Practical Guide

Structures, Unions, and File Handling in C – Complete Practical Guide

After mastering basics and pointers in C, the next important step is understanding how to work with complex data using structures and unions, and how to store data permanently using files. These topics are very important for real-world applications and technical interviews.

1. What is a Structure in C?

A structure is a user-defined data type that allows you to combine different types of data under one name. It is used when you want to represent a real-world entity such as a student, employee, or book.

struct Student {
    int id;
    char name[50];
    float marks;
};

Accessing Structure Members

struct Student s1 = {1, "Rahul", 85.5};
printf("ID: %d", s1.id);
printf("Name: %s", s1.name);
printf("Marks: %.2f", s1.marks);

2. Array of Structures

When we need to store information of multiple objects, we use an array of structures.

struct Student s[3];

3. Structure Pointer

A pointer to a structure stores the address of a structure variable.

struct Student *ptr = &s1;
printf("%s", ptr->name);

4. What is a Union in C?

A union is similar to a structure, but all members share the same memory location. Only one member can store a value at a time.

union Data {
    int i;
    float f;
    char c;
};

Difference Between Structure and Union

StructureUnion
Each member has separate memoryAll members share same memory
All values stored at onceOnly one value at a time
Uses more memoryUses less memory

5. File Handling in C

File handling allows data to be stored permanently in files. C provides built-in functions to create, read, write, and close files.

Opening a File

FILE *fp;
fp = fopen("data.txt", "w");

Writing to a File

fprintf(fp, "Welcome to C Programming");
fclose(fp);

Reading from a File

char text[100];
fp = fopen("data.txt", "r");
fgets(text, 100, fp);
printf("%s", text);
fclose(fp);

6. File Modes in C

  • "r" – Read
  • "w" – Write
  • "a" – Append
  • "r+" – Read and Write

7. Common Interview Questions

  • Why do we use structures in C?
  • What is the difference between structure and union?
  • What is FILE pointer?
  • Explain fopen(), fclose(), fprintf(), fscanf()

8. Real-World Uses

  • Student management systems
  • Employee records
  • Banking software
  • Database file storage

Conclusion

Structures, unions, and file handling are core parts of professional C programming. They help you organize complex data and store it permanently. Mastering these concepts will make you confident in projects and interviews.

Next Post: C++ Programming for Beginners – From Basics to Object-Oriented Concepts

Comments

Popular posts from this blog

Top 10 Free Coding Websites Every Beginner Should Use in 2026

Graph Data Structure – Complete Beginner to Advanced Guide with BFS, DFS and Examples

5 JavaScript Console Methods You're Not Using (But Should Be)