Mastering C Programming: A Complete Tutorial for Beginners and Beyond

46 0 0 0 0

📘 Chapter 6: File Handling and Advanced Topics in C

🧠 Introduction

C isn’t just limited to screen-based input/output operations. Real-world applications often need to read from and write to files—think of saving logs, storing user data, or exporting reports. C handles files using file pointers and standard I/O functions defined in the <stdio.h> header.

In this chapter, we’ll cover:

  • File handling basics
  • Reading and writing files
  • Error handling with files
  • Structures and unions
  • Enums and typedef
  • Preprocessors and macros

📂 Part 1: File Handling in C


🔹 What is File Handling?

File handling is a way to store data permanently on storage devices such as hard drives or SSDs. It allows a program to create, read, write, append, and modify data in files.


File Pointer

All file operations in C are done via a special pointer:

FILE *fp;

Defined in <stdio.h>, this FILE structure tracks information like the current position, the file descriptor, and buffering.


📋 File Modes

Mode

Meaning

Behavior

"r"

Read only

File must exist

"w"

Write only

Creates new file or truncates if exists

"a"

Append

Adds to the end; creates if file doesn’t exist

"r+"

Read + Write

File must exist

"w+"

Read + Write

Truncates or creates new file

"a+"

Read + Append

File created if doesn’t exist, appends on write


🔹 Opening a File

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

🔹 Closing a File

fclose(fp);


🔹 Writing to a File

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

fprintf(fp, "Hello World!\n");

fclose(fp);


🔹 Reading from a File

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

char line[100];

fgets(line, sizeof(line), fp);

printf("%s", line);

fclose(fp);


Example: Writing and Reading Numbers

#include <stdio.h>

 

int main() {

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

    for (int i = 1; i <= 5; i++) {

        fprintf(fp, "%d\n", i);

    }

    fclose(fp);

 

    fp = fopen("numbers.txt", "r");

    int num;

    while (fscanf(fp, "%d", &num) != EOF) {

        printf("%d ", num);

    }

    fclose(fp);

    return 0;

}


🔒 Error Handling

Always check if the file pointer is NULL:

if (fp == NULL) {

    printf("File not found or cannot be opened.\n");

    return 1;

}


🧱 Part 2: Structures and Unions


🔹 Structures in C

Structures allow grouping different types of variables under one name.

struct Person {

    char name[50];

    int age;

};

Usage:

struct Person p1 = {"Alice", 30};

printf("%s is %d years old", p1.name, p1.age);


📋 Table: Structure Example

Member

Type

Value

name

char[50]

"Alice"

age

int

30


🔹 Array of Structures

struct Person people[2] = {

    {"Alice", 30},

    {"Bob", 25}

};


🔹 Nested Structures

struct Date {

    int day, month, year;

};

 

struct Employee {

    char name[50];

    struct Date dob;

};


🔹 Pointers to Structures

struct Person *ptr = &p1;

printf("%s", ptr->name);


🔹 Unions in C

A union uses the same memory for all its members. Only one member is active at a time.

union Data {

    int i;

    float f;

    char str[20];

};

 

union Data d;

d.i = 10;


📋 Table: Structure vs Union

Feature

Structure

Union

Memory

Separate for each member

Shared between members

Access

All members simultaneously

One member at a time

Use Case

Grouping related data

Memory-efficient storage


🧮 Part 3: Enums and Typedef


🔹 Enums (Enumerations)

Enums assign names to a set of integer constants.

enum Color { RED, GREEN, BLUE };

  • RED = 0, GREEN = 1, BLUE = 2 by default
  • Can be customized:

enum Color { RED = 5, GREEN = 10, BLUE = 20 };


Example:

enum Day { MON, TUE, WED };

enum Day today = TUE;

printf("%d", today);  // Output: 1


🔹 Typedef

Used to create new names for existing data types.

typedef unsigned int uint;

Use Case:

uint age = 25;


️ Part 4: Preprocessor Directives and Macros


🔹 Preprocessors

These are instructions executed before compilation.

Examples:

Directive

Purpose

#include

Includes standard/user-defined headers

#define

Defines macros or constants

#ifdef

Conditional compilation


🔹 Macros

Macros are constants or functions replaced at compile time.

#define PI 3.14159

#define AREA(r) (PI * r * r)


Example:

#include <stdio.h>

#define SQUARE(x) ((x)*(x))

 

int main() {

    printf("%d", SQUARE(5));  // Output: 25

    return 0;

}


🧪 Sample Program: Store Struct Data in File

#include <stdio.h>

#include <stdlib.h>

 

struct Student {

    char name[50];

    int age;

};

 

int main() {

    struct Student s1 = {"John", 20};

 

    FILE *fp = fopen("student.dat", "wb");

    fwrite(&s1, sizeof(s1), 1, fp);

    fclose(fp);

 

    struct Student s2;

    fp = fopen("student.dat", "rb");

    fread(&s2, sizeof(s2), 1, fp);

    fclose(fp);

 

    printf("Name: %s, Age: %d", s2.name, s2.age);

    return 0;

}


🧠 Real-World Applications

Feature

Use Case

File Handling

Logging, saving settings, configuration files

Structures

Grouping records in databases or student systems

Unions

Efficient embedded device storage

Enums

Representing states or categories

Macros

Compile-time performance and portability


📋 Chapter Summary Table


Concept

Description

File I/O

Reading/writing data to files

Structure

Collection of heterogeneous data

Union

Memory-efficient structure

Enum

Named integer constants

Typedef

Alias for existing types

Macro

Compile-time constant or inline logic

Back

FAQs


1. Q: Is C still worth learning in 2025?

A: Absolutely. C is widely used in systems programming, embedded systems, and performance-critical applications.

2. Q: What are the prerequisites for learning C?

A: Just basic computer literacy. No prior programming knowledge is required.

3. Q: Which IDE is best for beginners in C?

 A: Code::Blocks or VS Code with a C plugin is great for beginners.

4. Q: Is C a compiled or interpreted language?

 A: C is a compiled language. It uses compilers like GCC or Clang.

5. Q: How long does it take to learn C?

A: With consistent practice, 4–8 weeks is sufficient to grasp core concepts.

6. Q: What’s the hardest part of C?

A: Pointers and manual memory management can be tricky for beginners.

7. Q: Can I use C to build web applications?

A: C is not typically used for web apps, but it can handle back-end processes or be integrated via CGI.

8. Q: Is C better than C++ or Python?

A: Each has its use. C is great for low-level control and speed, but C++ and Python offer more abstraction and ease of use.

9. Q: How do I run a C program?

A: Use a terminal/IDE to compile with gcc filename.c -o output and run with ./output.

10. Q: Where can I find C projects to practice?

A: GitHub, HackerRank, and open-source forums are great places to find beginner to advanced C projects.