Skip to main content
C Programming Basics
CHAPTER 17 Beginner

File Handling in C

Updated: May 17, 2026
5 min read

# CHAPTER 17

File Handling in C

1. Introduction

Until now, all data in our programs was stored in RAM. When the program exited, the data was lost forever (Volatile Memory). To make data permanent (Persistent Memory), we must save it to a file on the hard drive. C provides powerful built-in functions in <stdio.h> for File Handling.

2. Learning Objectives

By the end of this chapter, you will be able to:
  • Open files in different modes (read, write, append).
  • Use a FILE pointer.
  • Write text to files using fprintf() and fputs().
  • Read text from files using fscanf() and fgets().
  • Close files properly to prevent data corruption.

3. The FILE Pointer and fopen()

To interact with a file, you need a pointer of type FILE. You open a file using the fopen() function, which requires the file name and the "mode".

Common Modes:

  • "r" : Read mode. (Returns NULL if file doesn't exist).
  • "w" : Write mode. (Creates a new file. If the file exists, it erases all contents!).
  • "a" : Append mode. (Creates a new file or adds data to the end of an existing file).

c
1234567891011121314151617181920
#include <stdio.h>

int main() {
    FILE *filePtr;
    
    // Open file in Write mode
    filePtr = fopen("data.txt", "w");
    
    if (filePtr == NULL) {
        printf("Error opening file.\n");
        return 1;
    }
    
    printf("File opened successfully!\n");
    // We will write code here next...
    
    // Always close the file!
    fclose(filePtr); 
    return 0;
}

4. Writing to a File

To write formatted text to a file, use fprintf(). It works exactly like printf(), but takes the file pointer as its first argument.
c
1234567
FILE *filePtr = fopen("data.txt", "w");

if (filePtr != NULL) {
    fprintf(filePtr, "Hello, File!\n");
    fprintf(filePtr, "My age is %d\n", 25);
    fclose(filePtr);
}

5. Reading from a File

To read formatted text, use fscanf(). To read a full line (including spaces), use fgets().

Reading a full line using fgets():

c
123456789101112
FILE *filePtr = fopen("data.txt", "r");
char buffer[100];

if (filePtr != NULL) {
    // Read up to 99 characters until a newline or EOF is reached
    while (fgets(buffer, sizeof(buffer), filePtr) != NULL) {
        printf("%s", buffer); // Print the line to the screen
    }
    fclose(filePtr);
} else {
    printf("File not found!\n");
}

6. Mini Project: Notes Storage System

Let's build a program that asks the user for a note and saves it permanently to a text file.
c
12345678910111213141516171819202122232425262728
#include <stdio.h>

int main() {
    FILE *file;
    char note[200];

    // Use "a" (append) so we don't delete older notes!
    file = fopen("my_notes.txt", "a");

    if (file == NULL) {
        printf("Could not open file!\n");
        return 1;
    }

    printf("=== MY NOTES SYSTEM ===\n");
    printf("Enter a new note (max 200 chars): ");
    
    // Read the line including spaces
    fgets(note, sizeof(note), stdin);

    // Write it to the file
    fprintf(file, "- %s", note);
    
    printf("Note saved to my_notes.txt successfully!\n");

    fclose(file);
    return 0;
}

7. Memory-Level Explanation

When you call fopen(), the Operating System steps in. It locates the file on the hard drive (HDD/SSD) and loads a chunk of it into a temporary buffer in RAM. The FILE * pointer points to this buffer structure.

When you write using fprintf(), you are actually writing to the RAM buffer. It is only when you call fclose() (or the buffer fills up) that the OS "flushes" the buffer and physically writes the data to the hard drive. If you forget to call fclose() and the program crashes, your data may be lost!

8. Common Mistakes

  • Forgetting fclose(): Results in memory leaks and missing data in the file.
  • Using "w" instead of "a": You wanted to add a line, but "w" wiped the whole 10,000-line database!
  • Not checking for NULL: If you try to read a file that doesn't exist, fopen returns NULL. If you pass NULL to fgets, the program will crash (Segmentation Fault).

9. Exercises

  1. 1. Write a program that asks for the user's name and age, and writes it to users.txt.
  1. 2. Write a second program that opens users.txt in "r" mode and prints its contents to the screen.

10. MCQ Quiz with Answers

Question 1

What data type is required to manage a file in C?

Question 2

Which mode is used to add data to the end of an existing file?

Question 3

What does fopen("data.txt", "w") do if the file already exists?

Question 4

What does fopen() return if the file cannot be opened?

Question 5

Which function writes formatted data to a file?

Question 6

Which function is used to read a full line containing spaces from a file?

Question 7

Why is fclose() essential?

Question 8

Which mode opens a file for reading?

Question 9

If a file is opened in "r" mode, and it does not exist, what happens?

Q10. Can you use fprintf() to print to the screen? a) Yes, by passing stdout as the file pointer b) No, only to files Answer: a) Yes, by passing stdout as the file pointer

11. Interview Questions

  • Q: Explain the difference between text mode ("w") and binary mode ("wb") in C file handling.
  • Q: Why is it dangerous to ignore the return value of fopen()?
  • Q: Explain the concept of the file buffer and why fflush() or fclose() is necessary.

12. Summary

File handling allows data to persist after the program exits. We use a FILE * pointer and fopen() to access files in read ("r"), write ("w"), or append ("a") modes. fprintf and fgets handle writing and reading. Always remember to fclose() the file when finished!

13. Next Chapter Recommendation

In Chapter 18: Recursion in C, we will dive into one of the most mind-bending concepts in computer science: functions that call themselves.

Finish this Chapter

Save your progress on your learning path and prepare for coding interview challenges.

Discussion

Join the discussion

Log in or create a free account to participate.

Sort: ·