Working with Files in C Programming | Class 12 NEB Nepal

 

Introduction

File handling is a crucial concept in programming that allows us to store data permanently on disk. Unlike variables that lose their values when a program terminates, files enable us to preserve data for future use. In this lesson, we'll explore how C programming handles files, different types of file access, and various functions for file manipulation.

What is a Data File?

A data file is a collection of related information stored on a storage device (like a hard disk or SSD). In C programming, we use files to:

  • Store program output permanently
  • Read input data from external sources
  • Share data between different programs
  • Create databases and records

Think of a data file as a notebook where you can write information, read it later, add more content, or modify existing content.

Types of File Access

C supports two primary methods of accessing data in files:

1. Sequential File Access

In sequential access, data is read or written in a linear order, from beginning to end. It's like reading a book page by page—you must go through earlier pages to reach later ones.

Characteristics:

  • Simple and straightforward
  • Efficient for processing entire files
  • Must traverse through previous records to reach a specific record
  • Best for applications where all data needs to be processed

Example Use Cases:

  • Log files
  • Text documents
  • Report generation

2. Random File Access

Random access (also called direct access) allows you to jump directly to any position in the file without reading previous data. It's like using an index to jump to a specific page in a book.

Characteristics:

  • Faster access to specific records
  • Requires knowledge of record positions
  • More complex to implement
  • Ideal for database-like operations

Example Use Cases:

  • Student records system
  • Inventory management
  • Banking systems

File Manipulation Functions

C provides various functions for reading and writing different types of data. Let's explore the most important ones:

Character-Level Functions

putc() - Write a Character

int putc(int ch, FILE *fp);

Writes a single character to the file.

Example:

FILE *fp = fopen("output.txt", "w");
putc('A', fp);  // Writes 'A' to the file
fclose(fp);

getc() - Read a Character

int getc(FILE *fp);

Reads a single character from the file.

Example:

FILE *fp = fopen("input.txt", "r");
char ch = getc(fp);  // Reads one character
printf("Character read: %c\n", ch);
fclose(fp);

Integer-Level Functions

putw() - Write an Integer

int putw(int num, FILE *fp);

Writes an integer value to the file in binary format.

Example:

FILE *fp = fopen("numbers.dat", "w");
putw(100, fp);  // Writes integer 100
putw(200, fp);  // Writes integer 200
fclose(fp);

getw() - Read an Integer

int getw(FILE *fp);

Reads an integer value from the file.

Example:

FILE *fp = fopen("numbers.dat", "r");
int num1 = getw(fp);  // Reads first integer
int num2 = getw(fp);  // Reads second integer
printf("Numbers: %d, %d\n", num1, num2);
fclose(fp);

Formatted I/O Functions

fprintf() - Formatted Write

int fprintf(FILE *fp, const char *format, ...);

Writes formatted output to a file, similar to printf() but for files.

Example:

FILE *fp = fopen("student.txt", "w");
fprintf(fp, "Name: %s\n", "John Doe");
fprintf(fp, "Roll: %d\n", 101);
fprintf(fp, "Marks: %.2f\n", 85.5);
fclose(fp);

fscanf() - Formatted Read

int fscanf(FILE *fp, const char *format, ...);

Reads formatted input from a file, similar to scanf() but for files.

Example:

FILE *fp = fopen("student.txt", "r");
char name[50];
int roll;
float marks;

fscanf(fp, "Name: %s\n", name);
fscanf(fp, "Roll: %d\n", &roll);
fscanf(fp, "Marks: %f\n", &marks);

printf("Student: %s, Roll: %d, Marks: %.2f\n", name, roll, marks);
fclose(fp);

File Operations: The Complete Workflow

1. Opening a File

Before performing any operation, you must open a file using fopen():

FILE *fopen(const char *filename, const char *mode);

Common File Modes:

Mode Description Behavior
"r" Read Opens existing file for reading. Returns NULL if file doesn't exist.
"w" Write Creates new file or truncates existing file for writing.
"a" Append Opens or creates file for appending data at the end.
"r+" Read + Write Opens existing file for both reading and writing.
"w+" Write + Read Creates new file for reading and writing. Truncates if exists.
"a+" Append + Read Opens or creates file for reading and appending.

Example:

FILE *fp = fopen("data.txt", "r");
if (fp == NULL) {
    printf("Error: File cannot be opened!\n");
    return 1;
}

2. Reading from a File

Example: Reading character by character

FILE *fp = fopen("input.txt", "r");
char ch;

while ((ch = getc(fp)) != EOF) {
    printf("%c", ch);
}
fclose(fp);

Example: Reading formatted data

FILE *fp = fopen("marks.txt", "r");
int roll;
float marks;

while (fscanf(fp, "%d %f", &roll, &marks) != EOF) {
    printf("Roll: %d, Marks: %.2f\n", roll, marks);
}
fclose(fp);

3. Writing to a File

Example: Writing character by character

FILE *fp = fopen("output.txt", "w");
char text[] = "Hello, File!";

for (int i = 0; text[i] != '\0'; i++) {
    putc(text[i], fp);
}
fclose(fp);

Example: Writing formatted data

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

fprintf(fp, "%-10s %-5s %-10s\n", "Name", "Age", "City");
fprintf(fp, "%-10s %-5d %-10s\n", "Alice", 20, "Kathmandu");
fprintf(fp, "%-10s %-5d %-10s\n", "Bob", 22, "Pokhara");

fclose(fp);

4. Appending to a File

Appending adds new data to the end of an existing file without erasing previous content.

Example:

FILE *fp = fopen("log.txt", "a");

fprintf(fp, "New log entry at %s\n", "2025-11-17");
fprintf(fp, "Status: Success\n");

fclose(fp);

5. Closing a File

Always close files after operations to:

  • Save all buffered data
  • Free system resources
  • Prevent data corruption
fclose(fp);

Complete Working Example: Student Record System

Here's a practical program demonstrating file operations:

#include <stdio.h>
#include <stdlib.h>

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

// Function to write student records
void writeRecords() {
    FILE *fp = fopen("students.txt", "w");
    if (fp == NULL) {
        printf("Error opening file!\n");
        return;
    }
    
    struct Student s;
    int n;
    
    printf("Enter number of students: ");
    scanf("%d", &n);
    
    for (int i = 0; i < n; i++) {
        printf("\nEnter details for student %d:\n", i + 1);
        printf("Roll Number: ");
        scanf("%d", &s.roll);
        printf("Name: ");
        scanf("%s", s.name);
        printf("Marks: ");
        scanf("%f", &s.marks);
        
        fprintf(fp, "%d %s %.2f\n", s.roll, s.name, s.marks);
    }
    
    fclose(fp);
    printf("\nRecords saved successfully!\n");
}

// Function to read and display student records
void readRecords() {
    FILE *fp = fopen("students.txt", "r");
    if (fp == NULL) {
        printf("Error: File not found!\n");
        return;
    }
    
    struct Student s;
    
    printf("\n%-10s %-20s %-10s\n", "Roll", "Name", "Marks");
    printf("----------------------------------------\n");
    
    while (fscanf(fp, "%d %s %f", &s.roll, s.name, &s.marks) != EOF) {
        printf("%-10d %-20s %-10.2f\n", s.roll, s.name, s.marks);
    }
    
    fclose(fp);
}

// Function to append new records
void appendRecords() {
    FILE *fp = fopen("students.txt", "a");
    if (fp == NULL) {
        printf("Error opening file!\n");
        return;
    }
    
    struct Student s;
    
    printf("\nEnter details for new student:\n");
    printf("Roll Number: ");
    scanf("%d", &s.roll);
    printf("Name: ");
    scanf("%s", s.name);
    printf("Marks: ");
    scanf("%f", &s.marks);
    
    fprintf(fp, "%d %s %.2f\n", s.roll, s.name, s.marks);
    
    fclose(fp);
    printf("\nRecord appended successfully!\n");
}

int main() {
    int choice;
    
    while (1) {
        printf("\n=== Student Record System ===\n");
        printf("1. Write Records\n");
        printf("2. Read Records\n");
        printf("3. Append Record\n");
        printf("4. Exit\n");
        printf("Enter your choice: ");
        scanf("%d", &choice);
        
        switch (choice) {
            case 1:
                writeRecords();
                break;
            case 2:
                readRecords();
                break;
            case 3:
                appendRecords();
                break;
            case 4:
                printf("Exiting program...\n");
                exit(0);
            default:
                printf("Invalid choice!\n");
        }
    }
    
    return 0;
}

Important Points to Remember

  1. Always check if file opened successfully: Check if fopen() returns NULL
  2. Always close files: Use fclose() after operations
  3. Use appropriate file modes: Choose the correct mode based on your requirement
  4. Handle EOF properly: Check for End Of File when reading
  5. Binary vs Text mode: Add 'b' (e.g., "rb", "wb") for binary files
  6. Error handling: Always include error checking for robust programs
  7. Buffer flushing: Files are automatically flushed when closed or you can use fflush()

Practice Exercises

  1. Write a program to copy contents from one file to another
  2. Create a program to count the number of words, lines, and characters in a text file
  3. Implement a program to search for a specific student record by roll number
  4. Write a program to merge two sorted files into a third file
  5. Create a simple employee database with options to add, display, and delete records

Summary

File handling in C allows us to work with persistent data storage. We've learned about:

  • The concept of data files and their importance
  • Sequential vs random file access methods
  • Various file manipulation functions for different data types
  • Complete workflow: opening, reading, writing, and appending files

Mastering file operations is essential for creating practical applications that need to store and retrieve data beyond program execution.

Netra Koirala

Netra Koirala

Computer Science Educator

Passionate computer science educator and author. Provides free study notes, practical guides, and tutorials for Class 9, 10, 11, 12, and B.Sc CSIT students in Nepal. Years of teaching experience in computer science fundamentals.

Computer Science notes, tutorials, MCQs, and educational resources for Nepal students. Covering Class 9, SEE preparation, Class 11, Class 12, SLC, programming, DBMS, networking, HTML, JavaScript, PHP, OOP and more.

Featured Post

Grade 10 Computer Science: Specification Grid & Model Questions

Specification Grid & Model Questions of Computer Science | Grade 10 📚 Examination Resource Specification Grid & M...

Followers