Back to C Programming
2026-07-135 min read

File Handling in C

Learn File Handling in C step by step with clear examples and exercises.

Why This Matters

File handling is a crucial aspect of programming and plays an essential role in C programming. This guide will take you through the core concepts, worked examples, common mistakes, practice questions, and frequently asked questions about file handling in C.

Understanding File Handling

File handling allows you to read data from files, write data to files, create new files, and perform various operations on existing ones. These skills are vital for many real-world programming tasks, such as reading configuration files, saving user data, or processing large datasets. In addition, understanding file handling can help you avoid common pitfalls during your coding interviews.

Prerequisites

Before diving into file handling in C, you should have a good understanding of the following:

  • Basic C programming concepts (variables, loops, functions, etc.)
  • Understanding of data types and operators
  • Familiarity with standard input/output operations (printf, scanf)
  • Knowledge of basic data structures like arrays and strings

Core Concept

Opening a File

To open a file in C, you use the fopen() function. This function takes two arguments: the name of the file and the mode in which you want to open it. Here's an example:

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

In this example, we're opening a file named example.txt in read-only mode ("r"). The fopen() function returns a pointer to the opened file (fp), which you can use with other functions like fread() and fwrite().

Reading from a File

To read data from a file, you can use the fgets(), fscanf(), or fread() function. Here's an example using fgets():

char buffer[100];
size_t bytesRead = fgets(buffer, sizeof(buffer), fp);

In this example, we're reading up to 99 characters (leaving room for the null terminator) from the file into a buffer. The fgets() function returns the number of bytes read (excluding the null terminator).

Writing to a File

To write data to a file, you can use the fprintf(), fputs(), or fwrite() function. Here's an example using fprintf():

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

In this example, we're writing the string "Hello, World!" to the file pointed by fp.

Closing a File

After you finish working with a file, it's important to close it using the fclose() function. Here's an example:

fclose(fp);

In this example, we're closing the file pointed by fp.

File Modes

There are several modes you can use when opening a file with fopen(). Here are some common ones:

  • "r": Read-only mode (default if no mode is specified)
  • "w": Write-only mode; overwrites the existing file
  • "a": Append mode; adds data to the end of the file
  • "rb": Binary read mode
  • "wb": Binary write mode
  • "ab": Binary append mode

Working with Directories and Filesystem Operations

C also provides functions for working with directories, such as creating, removing, and listing files. These functions include mkdir(), rmdir(), opendir(), readdir(), and closedir().

Worked Example

Let's create a simple program that reads numbers from a file, calculates their sum, and writes the result to another file.

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

int main() {
FILE *inputFile = fopen("numbers.txt", "r");
FILE *outputFile = fopen("sum.txt", "w");

if (inputFile == NULL || outputFile == NULL) {
printf("Error: Unable to open files.\n");
return 1;
}

int sum = 0;
char buffer[10];

while (fgets(buffer, sizeof(buffer), inputFile)) {
int number = atoi(buffer);
sum += number;
}

fprintf(outputFile, "The sum is: %d\n", sum);

fclose(inputFile);
fclose(outputFile);

printf("Data processed successfully.\n");
return 0;
}

In this example, we're reading numbers from numbers.txt, calculating their sum, and writing the result to sum.txt.

Common Mistakes

  1. Forgetting to check for NULL after opening a file: Always check if fopen() returns a valid file pointer (not NULL) before using it with other functions.
FILE *fp = fopen("example.txt", "r");
if (fp == NULL) {
printf("Error: Unable to open the file.\n");
return 1;
}
  1. Not closing a file: Always close the file after you finish working with it using fclose(). Failing to do so can lead to memory leaks or other issues.
  1. Reading past the end of the file: When reading from a file, always check the return value of functions like fgets() and fread() to ensure you're not trying to read past the end of the file.
  1. Not handling errors properly: Always check for errors when working with files and handle them appropriately (e.g., by printing an error message or exiting the program).
  1. Misusing binary mode: Binary mode should be used only when working with binary files, as treating binary data as text can lead to unexpected results.

Practice Questions

  1. Write a program that reads numbers from a file and calculates their average. Save the result in another file.
  2. Modify the worked example to perform a different operation on each number (e.g., square the number).
  3. Create a program that reads a text file, replaces all occurrences of "apple" with "banana", and writes the modified text to another file.
  4. Write a program that lists all files in a specified directory.
  5. Write a program that removes all .txt files from a specified directory.

FAQ

  1. Why do I need to check for NULL after opening a file? Checking for NULL ensures that your program can handle cases where the file cannot be opened (e.g., if it doesn't exist, or you don't have permission to read/write it). Failing to do so may cause your program to crash or behave unexpectedly.
  1. What happens if I try to write to a file in write-only mode and the file already exists? If you open a file in write-only mode ("w") and the file already exists, its contents will be overwritten. To append data to an existing file, use "a" or "ab" mode instead.
  1. What is binary mode in C? Binary mode (indicated by the "b" suffix) is used when working with files that contain binary data, such as images or executable files. In text mode, characters are treated as ASCII values, which can lead to unexpected results when dealing with binary data.
  1. What is the difference between fgets() and fscanf()? fgets() reads a line from a file into a buffer, while fscanf() scans formatted input from a file. Both functions can be used for reading data from files, but they have different syntaxes and use cases.
  1. Why should I handle errors properly when working with files? Handling errors properly ensures that your program behaves gracefully in the event of an error (e.g., by printing an error message or exiting the program). Failing to do so can lead to unexpected behavior, crashes, or data loss.