×

Advanced Coding & Software Engineering Program

Duration: 1 Year (12 Months)

Join our premium 1-year program to master cutting-edge technologies and become an industry-ready Software Engineer!

Course Coverage

  • Languages: C, C++, Java, JavaScript, Python
  • Web Technologies: HTML, CSS, Bootstrap 5, MERN Stack, Full Stack Development
  • Databases: MySQL, MongoDB
  • Data Science Libraries: Pandas, NumPy
  • Development Tools: Visual Studio Code, IntelliJ IDEA, PyCharm, Postman, Git, GitHub
  • Cloud Platforms: Vercel, MongoDB Atlas

Program Highlights

  • Live Classes: Interactive sessions with real-time doubt resolution
  • Hands-On Sessions: Practical coding exercises to build real-world skills
  • Industry Experts: Learn from professionals with years of experience
  • Live Project: Work on real-world projects to apply your skills
  • Get Certificate: Earn a professional certificate upon program completion

Course Fee: Only ₹1020 / month
Limited Period Offer!

File Handling in C: Fun and Easy Guide from Basics to Advanced



Last Updated on: 27th Jul 2025 18:48:42 PM

Imagine your C program as a librarian, and files as notebooks where you store or read information. File handling in C lets your program write data to these notebooks (files) or read from them, making it possible to save information permanently. This tutorial covers File I/O (fopen, fscanf, fprintf, fclose, etc.), Reading and Writing Files, and Modes and File Operations, designed for your website to engage students with clear, real-life examples. We’ll go from beginner basics to advanced applications, using scanf and fgets for interactivity. Each example includes code, output, and a simple explanation to keep things fun and easy. Let’s start managing those notebooks!

 

1. What Is File Handling?

File handling in C is about reading from or writing to files on your computer, like jotting down notes in a notebook or reading someone else’s notes. Files store data (text, numbers, etc.) even after your program ends, unlike variables that disappear. It’s perfect for saving game scores, logs, or student records.

 

Why It’s Awesome:

  • Save data permanently (e.g., a high score list).

  • Read large datasets (e.g., a list of products).

  • Build real-world apps like diaries or databases.

 

Key Tools (from <stdio.h>):

  • fopen: Opens a notebook (file) to read or write.

  • fscanf / fgets: Reads notes from the notebook.

  • fprintf / fputs: Writes notes to the notebook.

  • fclose: Closes the notebook to keep it safe.

 

2. File Modes and Operations

 

2.1. File Modes

When you open a file with fopen, you choose a mode to decide how to use the notebook:

  Mode

   Description

   When It Fails

 "r"

 Read an existing file

 If the file doesn’t exist

 "w"

 Create a new file or overwrite an existing one

 Never (creates file if needed)

 "a"

 Append to the end of a file or create a new one

 Never (creates file if needed)

 "r+"

 Read and write an existing file

 If the file doesn’t exist

 "w+"

 Create or overwrite a file for reading/writing

 Never (creates file if needed)

 "a+"

 Read and append to a file or create a new one

 Never (creates file if needed)

 

Fun Fact: Think of "r" as borrowing a library book to read, "w" as getting a fresh notebook, and "a" as adding notes to the back of an existing one!

 

2.2. Key File Operations

These functions are your chef’s tools for managing the recipe book:

  Function

  Purpose

  Return Value

 fopen(filename, mode)

 Opens a file for reading/writing

 FILE* (or NULL if fails)

 fscanf(file, format, ...)

 Reads formatted data (numbers, words)

 Number of items read (or EOF)

 fprintf(file, format, ...)

 Writes formatted data to the file

 Number of characters written

 fgets(str, size, file)

 Reads a line of text

 String (or NULL at end/error)

 fputs(str, file)

 Writes a string to the file

 Non-negative on success

 fclose(file)

 Closes the file, saving changes

 0 on success, EOF on error

 feof(file)

 Checks if you’re at the end of the file

Non-zero if at end, 0 otherwise

 

3. Getting Started: Writing to a File

Let’s start by writing a message to a notebook (file) using fprintf. This program asks the user for a message and saves it to a file called diary.txt.

#include <stdio.h>
#include <string.h>
int main() {
    char message[100];
    printf("Write a diary entry: ");
    fgets(message, 100, stdin);
    message[strcspn(message, "\n")] = '\0'; // Remove newline
    
    // Open the notebook in write mode
    FILE *file = fopen("diary.txt", "w");
    if (file == NULL) {
        printf("Oops! Couldn't open the diary!\n");
        return 1;
    }
    
    // Write the message
    fprintf(file, "Diary Entry: %s\n", message);
    
    // Close the notebook
    fclose(file);
    printf("Your entry was saved to diary.txt!\n");
    return 0;
}

 

Output (example user input: Feeling great today!):

Write a diary entry: Feeling great today!
Your entry was saved to diary.txt!

 

File Content (diary.txt):

Diary Entry: Feeling great today!

 

What’s Happening?

  • The user types a message using fgets, and we remove the newline with strcspn.

  • fopen("diary.txt", "w") creates or overwrites diary.txt for writing.

  • If fopen fails (returns NULL), we show an error.

  • fprintf writes the message to the file, like jotting it in a notebook.

  • fclose saves and closes the file to keep it safe.

 

Why It’s Fun: It’s like writing a secret diary entry that stays saved even after the program ends!

 

4. Reading from a File

Now, let’s read that diary entry back using fgets. This program reads and displays the content of diary.txt.

#include <stdio.h>
int main() {
    char line[100];
    
    // Open the notebook in read mode
    FILE *file = fopen("diary.txt", "r");
    if (file == NULL) {
        printf("Oops! Couldn't find or open diary.txt!\n");
        return 1;
    }
    
    printf("Reading your diary:\n");
    // Read lines until the end
    while (fgets(line, 100, file) != NULL) {
        printf("%s", line);
    }
    
    // Close the notebook
    fclose(file);
    return 0;
}

 

Output (assuming diary.txt from the previous example):

Reading your diary:
Diary Entry: Feeling great today!

 

What’s Happening?

  • fopen("diary.txt", "r") opens the file for reading.

  • If the file doesn’t exist or can’t be opened, we show an error.

  • fgets reads up to 100 characters (or until a newline) and stops when it hits the end (NULL).

  • Each line is printed with printf.

  • fclose closes the file to free resources.

 

Why It’s Fun: It’s like sneaking a peek at your old diary entries!

 

5. Appending to a File

What if you want to add more entries without erasing the old ones? Use append mode ("a"). This program adds a new score to a high score list in scores.txt.

#include <stdio.h>
int main() {
    char player[50];
    int score;
    
    printf("Enter player name: ");
    fgets(player, 50, stdin);
    player[strcspn(player, "\n")] = '\0';
    
    printf("Enter score: ");
    scanf("%d", &score);
    
    // Open in append mode
    FILE *file = fopen("scores.txt", "a");
    if (file == NULL) {
        printf("Oops! Couldn't open scores.txt!\n");
        return 1;
    }
    
    // Append the score
    fprintf(file, "%s: %d\n", player, score);
    
    fclose(file);
    printf("Score added to scores.txt!\n");
    return 0;
}

 

Output (example user input: Alice, 500):

Enter player name: Alice
Enter score: 500
Score added to scores.txt!

 

File Content (scores.txt after running twice with inputs: Alice, 500; Bob, 600):

Alice: 500
Bob: 600

 

What’s Happening?

  • The user enters a player name (fgets) and score (scanf).

  • fopen("scores.txt", "a") opens the file in append mode, adding to the end.

  • fprintf writes the new score without overwriting existing data.

  • fclose saves the changes.

 

Why It’s Fun: It’s like adding your name to a leaderboard in a game, keeping all previous scores!

 

6. Advanced Example: Student Record System

Let’s build a real-life student record system that lets users add student records (name and grade) to a file, read and display all records, and search for a student by name. This uses fscanf, fprintf, and multiple file modes in a fun, interactive app.

 

#include <stdio.h>
#include <string.h>
struct Student {
    char name[50];
    float grade;
};
void addStudent(FILE *file) {
    struct Student student;
    printf("Enter student name: ");
    fgets(student.name, 50, stdin);
    student.name[strcspn(student.name, "\n")] = '\0';
    
    printf("Enter grade (0-100): ");
    scanf("%f", &student.grade);
    getchar(); // Clear newline
    
    file = fopen("students.txt", "a");
    if (file == NULL) {
        printf("Oops! Couldn't open students.txt!\n");
        return;
    }
    
    fprintf(file, "%s %.2f\n", student.name, student.grade);
    fclose(file);
    printf("Student added!\n");
}
void displayStudents() {
    struct Student student;
    FILE *file = fopen("students.txt", "r");
    if (file == NULL) {
        printf("No student records found!\n");
        return;
    }
    
    printf("\nStudent Records:\n");
    while (fscanf(file, "%49s %f", student.name, &student.grade) == 2) {
        printf("Name: %s, Grade: %.2f\n", student.name, student.grade);
    }
    
    fclose(file);
}
void searchStudent() {
    char searchName[50];
    struct Student student;
    int found = 0;
    
    printf("Enter name to search: ");
    fgets(searchName, 50, stdin);
    searchName[strcspn(searchName, "\n")] = '\0';
    
    FILE *file = fopen("students.txt", "r");
    if (file == NULL) {
        printf("No student records found!\n");
        return;
    }
    
    while (fscanf(file, "%49s %f", student.name, &student.grade) == 2) {
        if (strstr(student.name, searchName) != NULL) {
            printf("Found: %s, Grade: %.2f\n", student.name, student.grade);
            found = 1;
        }
    }
    
    if (!found) {
        printf("No student found with name '%s'.\n", searchName);
    }
    
    fclose(file);
}
int main() {
    int choice;
    FILE *file = NULL;
    
    do {
        printf("\nStudent Record System:\n");
        printf("1. Add Student\n");
        printf("2. Display All Students\n");
        printf("3. Search Student\n");
        printf("4. Exit\n");
        printf("Choose: ");
        scanf("%d", &choice);
        getchar(); // Clear newline
        
        switch (choice) {
            case 1:
                addStudent(file);
                break;
            case 2:
                displayStudents();
                break;
            case 3:
                searchStudent();
                break;
            case 4:
                printf("Goodbye!\n");
                break;
            default:
                printf("Invalid choice! Try again.\n");
        }
    } while (choice != 4);
    
    return 0;
}

 

Output (example user interaction):

Student Record System:
1. Add Student
2. Display All Students
3. Search Student
4. Exit
Choose: 1

 

Enter student name: Alice
Enter grade (0-100): 85.5
Student added!

 

Student Record System:
1. Add Student
2. Display All Students
3. Search Student
4. Exit
Choose: 1

 

Enter student name: Bob
Enter grade (0-100): 92.0
Student added!

 

Student Record System:
1. Add Student
2. Display All Students
3. Search Student
4. Exit
Choose: 2

 

Student Records:
Name: Alice, Grade: 85.50
Name: Bob, Grade: 92.00

 

Student Record System:
1. Add Student
2. Display All Students
3. Search Student
4. Exit
Choose: 3

 

Enter name to search: Alice
Found: Alice, Grade: 85.50

 

Student Record System:
1. Add Student
2. Display All Students
3. Search Student
4. Exit
Choose: 4


Goodbye!

 

File Content (students.txt):

Alice 85.50
Bob 92.00

 

What’s Happening?

  • The program uses a Student structure to store name and grade.

  • Add Student: Opens students.txt in append mode ("  a"), writes a new record with fprintf, and closes the file.

  • Display Students: Opens the file in read mode ("r"), uses fscanf to read name and grade pairs, and prints them until the end (feof).

  • Search Student: Reads the file with fscanf, using strstr to find names containing the search term.

  • A menu loop with scanf and getchar() handles user choices.

  • Files are opened and closed for each operation to ensure safety.

 

Why It’s Fun: It’s like running a school database where you can add, view, and find student records, just like a real registrar!

 

7. Tips to Be a File Handling Pro

  • Check fopen: If it returns NULL, the file couldn’t be opened—handle it!

  • Close Files: Always use fclose to save changes and free resources.

  • Choose the Right Mode: Use "r" for reading, "w" for fresh files, "a" for adding.

  • Validate Input: Ensure user inputs (e.g., names) fit in buffers to avoid overflow.

  • Use fscanf Carefully: Check its return value to ensure correct data reading.

  • Keep Files Organized: Use clear file names like diary.txt or students.txt.

 

8. Why File Handling Rocks

File handling in C is amazing because:

  • Saves Data Forever: Keep scores, notes, or records even after your program ends.

  • Handles Big Data: Read or write large datasets like logs or lists.

  • Powers Real Apps: Build diaries, databases, or game save systems.

 

Fun Challenge: Try adding a “delete student” option to the record system or create a file-based to-do list. Play with files and share your cool projects in the comments below!

Happy coding, and have fun with your file-handling adventures!


Online - Chat Now
Let’s Connect

Inquiry Sent!

Your message has been successfully sent. We'll get back to you soon!

iKeySkills Logo