File Handling
When a program ends, all data stored in memory is lost. Learn how File Handling allows C programs to create, read, write, and permanently store data.
Introduction
So far, all the data in our programs has been stored in variables and arrays. However, when the program ends, all the data stored in memory is lost. For a Student Management System or Banking Application, if this information disappears every time the program closes, the software becomes useless. To permanently store information, C provides File Handling.
What is File Handling?
File Handling is the process of creating, opening, reading, writing, updating, and closing files. Files allow data to be stored permanently on storage devices such as hard disks or SSDs. Unlike variables, file data remains available even after the program terminates.
Why Do We Need File Handling?
Without File Handling
With File Handling
Real-World Analogy
Imagine a notebook. Instead of memorizing important information, you write it down. Even after closing the notebook, the information remains. Similarly, files permanently store information on a computer.
+----------------------+
| Student Records |
| - Rahul |
| - Amit |
| - Priya |
+----------------------+
(Data remains even when closed)Characteristics & Types of Files
Files store data permanently, can be created, modified, or deleted, and are stored on secondary storage devices. In C, files are generally classified into two categories.
Text Files
Store information in a human-readable format, such as .txt, .csv, and .c files. Examples include notes, configuration files, and source code.
Binary Files
Store information in binary format, such as .exe, .jpg, and .mp3 files. Their contents cannot normally be read directly using a text editor.
File Operations
File handling mainly consists of six core operations.
Create
Create a new file.
Open
Open an existing file.
Read
Read data from the file.
Write
Write data into the file.
Append
Add data to the end of the file.
Close
Close the file safely.
File Pointer & Header File
C uses a File Pointer to work with files. A file pointer keeps track of the current position inside a file. The data type used is FILE *fp;, where FILE is a predefined type provided by the C standard library and fp is the file pointer variable.
All standard file handling functions used in this lesson are declared in the stdio.h header file.
#include <stdio.h>
FILE *fp;Opening a File & File Modes
Before reading from or writing to a file, the file must be opened using the fopen() function.
FILE *fp = fopen("filename", "mode");
// If successful, returns a valid file pointer.
// If it fails, returns NULL.The second parameter specifies how the file will be used.
| Mode | Description |
|---|---|
| "r" | Read an existing file |
| "w" | Write to a file; creates a new file or truncates an existing file |
| "a" | Append data at the end of a file |
| "r+" | Read and write an existing file |
| "w+" | Read and write; creates a new file or truncates an existing file |
| "a+" | Read and append data |
Writing, Reading, and Closing
Writing to a File
Use fprintf(), fputs(), or fputc() to store information in a file.
Reading from a File
Use fscanf(), fgets(), or fgetc() to retrieve information from an existing file.
After all operations are complete, always close the file using fclose(fp);. This flushes pending buffered output, releases system resources, and helps prevent file-handling problems.
File Handling Process
Example: Writing to a File
#include <stdio.h>
int main()
{
FILE *fp;
fp = fopen("student.txt", "w");
if (fp == NULL)
{
printf("Unable to open file.");
return 1;
}
fprintf(fp, "Welcome to C Programming");
fclose(fp);
return 0;
}Line-by-Line Explanation
FILE *fp;
Declares a file pointer named fp. This pointer will be used to access the file.
fp = fopen("student.txt", "w");
Opens student.txt in Write Mode. If the file does not exist, it is created. If it already exists, its previous contents are removed.
if (fp == NULL)
Checks whether the file was opened successfully. If fopen() fails, it returns NULL and the program stops before attempting file operations.
fprintf(fp, "Welcome to C Programming");
Writes the specified text into the file using the file pointer. After successful execution, the file contains the text.
fclose(fp);
Closes the file, flushes pending buffered output, and releases the resources associated with the file stream.
Execution Flow & Memory Representation
FILE Pointer: fp
│
▼
student.txt
----------------------------
Welcome to C Programming
----------------------------
The file pointer connects the program
to the opened file stream.Advantages & Real-World Applications
Advantages
Real-World Applications
Common Beginner Mistakes
Always close the file after completing operations using fclose().
Opening a file in "w" mode when you only want to read it can erase its previous contents. Choose the file mode carefully.
fopen() may fail if the file cannot be opened. Always check whether the returned file pointer is NULL before performing file operations.
Most file handling functions require a valid file pointer to know which open file stream to operate on.
Best Practices
- Always check whether fopen() succeeds by checking for NULL.
- Close every successfully opened file using fclose().
- Use the correct file mode for the intended operation.
- Keep file names meaningful and descriptive.
- Handle file errors properly to prevent incorrect operations.
- Avoid leaving files open unnecessarily.
Frequently Asked Questions
What is file handling?
File handling is the process of creating, opening, reading, writing, updating, and closing files.
Why is file handling important?
It allows programs to store data permanently so the information remains available after the program ends.
Which header file is required for file handling?
#include <stdio.h>
What is a file pointer?
A file pointer is a variable of type FILE * used to access and manage an open file stream.
Which function opens a file?
fopen().
Which function closes a file?
fclose().
Key Takeaways
- File handling enables permanent data storage.
- Files can be text files or binary files.
- FILE * is used to access an open file stream.
- fopen() opens a file.
- fprintf() can write formatted data to a file.
- Functions such as fscanf(), fgets(), and fgetc() can read data from files.
- fclose() closes the file and releases associated resources.
- Always check whether fopen() returned NULL before using the file pointer.
Summary
File Handling is one of the most important features of C programming because it allows applications to store and retrieve data permanently. Unlike variables, whose values are lost when a program terminates, files preserve information for future use. By understanding file pointers, file modes, and standard file handling functions, programmers can build practical applications such as student management systems, banking software, inventory systems, and many other real-world programs that require persistent data storage.