
Chapter 16: File Handling
📚 C Programming – Complete Course Roadmap
⬅ Previous Chapter | Current Chapter: Structures and Unions | Next Chapter ➜
Author: Mujtaba Ansari
File Handling in C Programming: Complete Guide with Syntax, Functions, Examples & Programs
Want to store, read, and manage data beyond your program’s runtime? Learn File Handling in C and discover how files make your programs more powerful and practical.
In C programming, data stored in variables is generally available only while the program is running. Once the program ends, that data is lost. File Handling provides a way to store data permanently in files so that it can be accessed and processed later.
In this complete guide, you will learn File Handling in C, file types, file opening modes, important file functions, sequential and random access, and practical C programs with examples.
Key Benefits:
- Store data permanently
- Read and write files easily
- Update and manage existing data
- Handle large amounts of information
- Build practical, real-world C applications
What is File Handling in C?
A file is a collection of data stored on a storage device such as a hard disk, SSD, or other secondary storage.
File Handling in C is the process of creating, opening, reading, writing, updating, appending, and closing files using C programs.
Unlike temporary data stored in variables, data written to a file can remain available even after the program terminates. This is known as persistent data storage.
Why is File Handling Important?
File Handling is useful when a program needs to:
- Store data permanently
- Read previously stored information
- Add new data to an existing file
- Update or process stored records
- Manage large amounts of information
- Transfer or copy data between files
- Build practical applications such as student records, billing systems, employee databases, and inventory systems
File Handling Functions in C
C provides several functions through the standard <stdio.h> library for working with files.
| Function | Purpose |
|---|---|
fopen() | Opens or creates a file |
fclose() | Closes an opened file |
fgetc() | Reads a single character from a file |
fputc() | Writes a single character to a file |
fprintf() | Writes formatted data to a file |
fscanf() | Reads formatted data from a file |
fread() | Reads blocks of binary data |
fwrite() | Writes blocks of binary data |
fseek() | Moves the file position indicator |
ftell() | Returns the current file position |
rewind() | Moves the file position to the beginning |
feof() | Checks whether the end of a file has been reached |
Note: Older C textbooks sometimes discuss
getw()andputw(). They are not part of the modern standard C approach and are generally better avoided in new programs. Usefread(),fwrite(),fprintf(), andfscanf()according to the type of data being processed.
File Pointer in C
Before performing file operations, we generally use a file pointer.
Syntax
FILE *fp;
Here:
FILEis a type defined in<stdio.h>.fpis a file pointer.- The pointer is used by C file functions to work with the opened file.
For example:
FILE *fp;
fp = fopen("student.txt", "r");
Opening a File Using fopen()
The fopen() function is used to open an existing file or create a new file depending on the selected mode.
Syntax
FILE *fopen(const char *filename, const char *mode);
Example:
FILE *fp;
fp = fopen("student.txt", "w");
If the file cannot be opened, fopen() returns NULL.
Therefore, it is good practice to check the file pointer:
if (fp == NULL)
{
printf("Unable to open the file.");
}
File Opening Modes in C
The mode tells C what operation you want to perform on the file.
| Mode | Description |
|---|---|
"r" | Opens an existing file for reading |
"w" | Opens a file for writing; creates a new file or overwrites an existing file |
"a" | Opens a file for appending data at the end |
"r+" | Opens an existing file for reading and writing |
"w+" | Opens a file for reading and writing; existing contents are overwritten |
"a+" | Opens a file for reading and appending |
For binary files, b can be added:
"rb"
"wb"
"ab"
"rb+"
"wb+"
"ab+"
Closing a File Using fclose()
After completing file operations, the file should be closed using fclose().
Syntax
fclose(fp);
Example:
FILE *fp;
fp = fopen("student.txt", "r");
if (fp != NULL)
{
/* File operations */
fclose(fp);
}
Closing a file helps ensure that buffered data is properly written and releases the associated resources.
Important: The correct function name is
fclose(), notfclosed().
Reading a Character Using fgetc()
The fgetc() function reads one character at a time from a file.
Syntax
ch = fgetc(fp);
A common pattern for reading until the end of a file is:
int ch;
while ((ch = fgetc(fp)) != EOF)
{
putchar(ch);
}
Why use int instead of char?
fgetc() returns either the character read or the special value EOF. Therefore, the receiving variable should normally be declared as int.
Writing a Character Using fputc()
The fputc() function writes one character to a file.
Syntax
fputc(ch, fp);
Example:
FILE *fp;
fp = fopen("data.txt", "w");
if (fp != NULL)
{
fputc('A', fp);
fclose(fp);
}
Writing Formatted Data Using fprintf()
fprintf() works similarly to printf(), but instead of displaying the formatted output on the screen, it writes it to a file.
Syntax
fprintf(fp, "format", values);
Example:
fprintf(fp, "Name: %s\nAge: %d\n", name, age);
This is useful for storing structured text data.
Reading Formatted Data Using fscanf()
fscanf() reads formatted data from a file.
Syntax
fscanf(fp, "format", &variables);
Example:
fscanf(fp, "%d %s", &roll, name);
It is particularly useful when the file contains data in a predictable format.
Example 1: Create a File and Store Student Names
The following program creates stud.txt, accepts student names from the user, and then displays the contents of the file.
#include <stdio.h>
int main(void)
{
FILE *fp;
int ch;
fp = fopen("stud.txt", "w");
if (fp == NULL)
{
printf("Unable to create file.\n");
return 1;
}
printf("Enter student names.\n");
printf("Press Ctrl+D on Linux/macOS or Ctrl+Z followed by Enter on Windows to finish.\n");
while ((ch = getchar()) != EOF)
{
fputc(ch, fp);
}
fclose(fp);
fp = fopen("stud.txt", "r");
if (fp == NULL)
{
printf("Unable to open file.\n");
return 1;
}
printf("\nContents of stud.txt:\n");
while ((ch = fgetc(fp)) != EOF)
{
putchar(ch);
}
fclose(fp);
return 0;
}
How this program works
- The file
stud.txtis opened in"w"mode. - Student names are entered from the keyboard.
fputc()writes the characters to the file.- The file is closed.
- The same file is opened in
"r"mode. fgetc()reads the contents character by character.putchar()displays the contents on the screen.- Finally, the file is closed.
Example 2: Count Uppercase and Lowercase Letters in a File
This program reads stud.txt and counts the total uppercase and lowercase letters.
#include <stdio.h>
int main(void)
{
FILE *fp;
int ch;
int uppercase = 0;
int lowercase = 0;
fp = fopen("stud.txt", "r");
if (fp == NULL)
{
printf("File does not exist or cannot be opened.\n");
return 1;
}
printf("Contents of stud.txt:\n");
while ((ch = fgetc(fp)) != EOF)
{
putchar(ch);
if (ch >= 'A' && ch <= 'Z')
{
uppercase++;
}
else if (ch >= 'a' && ch <= 'z')
{
lowercase++;
}
}
printf("\n\nTotal uppercase letters = %d\n", uppercase);
printf("Total lowercase letters = %d\n", lowercase);
fclose(fp);
return 0;
}
Example Output
Contents of stud.txt:
Rahul
AMIT
Neha
Total uppercase letters = 5
Total lowercase letters = 9
The exact count depends on the contents of the file.
Example 3: Copy One File into Another File
File Handling can also be used to copy the contents of one file into another.
The following program copies stud.txt into copy.txt.
#include <stdio.h>
int main(void)
{
FILE *source;
FILE *destination;
int ch;
source = fopen("stud.txt", "r");
if (source == NULL)
{
printf("Source file cannot be opened.\n");
return 1;
}
destination = fopen("copy.txt", "w");
if (destination == NULL)
{
printf("Destination file cannot be created.\n");
fclose(source);
return 1;
}
while ((ch = fgetc(source)) != EOF)
{
fputc(ch, destination);
}
fclose(source);
fclose(destination);
printf("File copied successfully.\n");
return 0;
}
Key Concept
Here:
sourcepoints tostud.txt.destinationpoints tocopy.txt.fgetc()reads each character.fputc()writes each character into the destination file.
Example 4: Store Even and Odd Numbers in Separate Files
The following program accepts numbers, stores them in numbers.txt, and then separates them into even.txt and odd.txt.
#include <stdio.h>
int main(void)
{
FILE *input;
FILE *evenFile;
FILE *oddFile;
int number;
input = fopen("numbers.txt", "w");
if (input == NULL)
{
printf("Unable to create numbers.txt\n");
return 1;
}
printf("Enter numbers (enter 0 to stop):\n");
while (1)
{
scanf("%d", &number);
if (number == 0)
{
break;
}
fprintf(input, "%d\n", number);
}
fclose(input);
input = fopen("numbers.txt", "r");
evenFile = fopen("even.txt", "w");
oddFile = fopen("odd.txt", "w");
if (input == NULL || evenFile == NULL || oddFile == NULL)
{
printf("Error opening files.\n");
if (input != NULL)
fclose(input);
if (evenFile != NULL)
fclose(evenFile);
if (oddFile != NULL)
fclose(oddFile);
return 1;
}
while (fscanf(input, "%d", &number) == 1)
{
if (number % 2 == 0)
{
fprintf(evenFile, "%d\n", number);
}
else
{
fprintf(oddFile, "%d\n", number);
}
}
fclose(input);
fclose(evenFile);
fclose(oddFile);
printf("Even and odd numbers have been stored successfully.\n");
return 0;
}
Why this version is better
The original notes used getw() and putw(). For a modern C tutorial, using fprintf() and fscanf() makes the example easier to understand and avoids relying on older/non-standard functions.
Storing Structures in a File
File Handling becomes especially useful when working with structures.
For example, a student record can contain:
- Roll number
- Name
- Marks
A structure can group these values together.
struct Student
{
int roll;
char name[50];
float marks;
};
Example 5: Store and Display Student Records
The following program stores five student records in a text file and then reads them back.
#include <stdio.h>
struct Student
{
int roll;
char name[50];
float marks;
};
int main(void)
{
FILE *fp;
struct Student student;
int i;
fp = fopen("student_records.txt", "w");
if (fp == NULL)
{
printf("Unable to create file.\n");
return 1;
}
for (i = 1; i <= 5; i++)
{
printf("\nEnter details of Student %d\n", i);
printf("Roll Number: ");
scanf("%d", &student.roll);
printf("Name: ");
scanf("%49s", student.name);
printf("Marks: ");
scanf("%f", &student.marks);
fprintf(fp, "%d %s %.2f\n",
student.roll,
student.name,
student.marks);
}
fclose(fp);
fp = fopen("student_records.txt", "r");
if (fp == NULL)
{
printf("Unable to open file.\n");
return 1;
}
printf("\n--- Student Records ---\n");
while (fscanf(fp, "%d %49s %f",
&student.roll,
student.name,
&student.marks) == 3)
{
printf("\nRoll Number: %d", student.roll);
printf("\nName: %s", student.name);
printf("\nMarks: %.2f\n", student.marks);
}
fclose(fp);
return 0;
}
Note:
scanf("%49s", student.name)reads a single-word name. If you want to accept names containing spaces, such asRahul Kumar, a different input approach such asfgets()should be used.
Sequential File Access
In sequential access, data is generally processed from the beginning of the file toward the required position.
For example, if you want to read the fifth record, the program normally processes the earlier records first.
Functions such as:
fgetc()
fscanf()
are commonly used for sequential reading.
Example
Record 1 → Record 2 → Record 3 → Record 4 → Record 5
This approach is simple and useful for many text-file operations.
Random Access in C
Random access allows the file position indicator to be moved directly to a particular location in a file.
Instead of always starting from the beginning, a program can move the file position using functions such as:
fseek()ftell()rewind()
This can be useful when working with files where specific positions need to be accessed.
fseek() Function in C
The fseek() function changes the current position of the file position indicator.
Syntax
fseek(fp, offset, origin);
Where:
fp= file pointeroffset= number of bytes to moveorigin= reference position
The standard constants used for origin are:
SEEK_SET
SEEK_CUR
SEEK_END
They represent:
| Constant | Meaning |
|---|---|
SEEK_SET | Beginning of the file |
SEEK_CUR | Current position |
SEEK_END | End of the file |
Example
fseek(fp, 50L, SEEK_SET);
This moves the file position to an offset of 50 bytes from the beginning.
Another example:
fseek(fp, -7L, SEEK_CUR);
This attempts to move the position 7 bytes backward from the current position.
Important: The meaning of byte offsets can be more complicated for text streams. For portable random access, binary files are generally easier to reason about.
ftell() Function in C
The ftell() function returns the current position of the file position indicator.
Syntax
long position;
position = ftell(fp);
Example
#include <stdio.h>
int main(void)
{
FILE *fp;
long position;
fp = fopen("book.txt", "r");
if (fp == NULL)
{
printf("Unable to open file.\n");
return 1;
}
fseek(fp, 50L, SEEK_SET);
position = ftell(fp);
printf("Current file position: %ld\n", position);
fclose(fp);
return 0;
}
rewind() Function in C
The rewind() function moves the file position indicator back to the beginning of the file.
Syntax
rewind(fp);
It is conceptually similar to:
fseek(fp, 0L, SEEK_SET);
Example
rewind(fp);
After this statement, reading from the file starts again from the beginning.
Text Files vs Binary Files
C programs can work with both text files and binary files.
Text File
A text file stores information in a form that can generally be viewed using a text editor.
Examples:
students.txt
employees.csv
data.txt
Functions such as:
fprintf()
fscanf()
fgetc()
fputc()
are commonly used with text files.
Binary File
Binary files store data as bytes rather than human-readable text.
Functions such as:
fread()
fwrite()
are commonly used for binary data.
Example:
fwrite(&student, sizeof(student), 1, fp);
and:
fread(&student, sizeof(student), 1, fp);
Binary files can be useful when storing structures or other data in a compact machine-readable format.
File Handling with Binary Data
A simple binary-file example:
#include <stdio.h>
struct Student
{
int roll;
char name[50];
float marks;
};
int main(void)
{
FILE *fp;
struct Student student = {101, "Zain", 85.5};
fp = fopen("student.dat", "wb");
if (fp == NULL)
{
printf("Unable to create file.\n");
return 1;
}
fwrite(&student, sizeof(student), 1, fp);
fclose(fp);
printf("Student record stored successfully.\n");
return 0;
}
Here, fwrite() writes the structure directly to the binary file.
Important Points to Remember in File Handling
While working with files in C, keep these points in mind:
- Always include the
<stdio.h>header. - Declare a file pointer using
FILE *. - Use
fopen()to open or create a file. - Always check whether
fopen()returnedNULL. - Select the correct file mode.
- Use
fgetc()andfputc()for character-based operations. - Use
fprintf()andfscanf()for formatted text data. - Use
fread()andfwrite()for binary data. - Close files using
fclose()after completing operations. - Use
fseek(),ftell(), andrewind()when file-position control is required. - Use
intwhen storing the result offgetc()because it must be able to representEOF. - Be careful with
"w"mode because it can overwrite an existing file.
Common File Handling Errors in C
Beginners often make these mistakes:
1. Using fclosed() Instead of fclose()
Incorrect:
fclosed(fp);
Correct:
fclose(fp);
2. Not Checking fopen()
Always check:
if (fp == NULL)
{
printf("Unable to open file.\n");
}
3. Using char for fgetc() Result
Avoid:
char ch;
while ((ch = fgetc(fp)) != EOF)
Prefer:
int ch;
while ((ch = fgetc(fp)) != EOF)
4. Forgetting to Close the File
Always close the file after use:
fclose(fp);
5. Accidentally Overwriting a File
Opening a file using:
fopen("data.txt", "w");
can erase the previous contents.
If you want to add data at the end, use:
fopen("data.txt", "a");
File Handling vs Normal Variables
| Normal Variable | File |
|---|---|
| Usually stores temporary program data | Stores data persistently |
| Data generally exists during program execution | Data remains after program termination |
| Suitable for temporary calculations | Suitable for permanent records |
| Limited by program memory | Can store much larger datasets |
| Data is lost when the program ends unless saved elsewhere | Data can be reopened and processed later |
Real-World Applications of File Handling
File Handling is an important concept because many real-world programs need persistent data.
Examples include:
- Student Management Systems
- Employee Management Systems
- Library Management Systems
- Billing Software
- Inventory Management Systems
- Banking Applications
- Customer Record Systems
- Result Management Systems
- Log Files
- Configuration Files
- Data Export and Import Systems
Frequently Asked Questions (FAQ)
What is File Handling in C?
File Handling in C is the process of creating, opening, reading, writing, updating, and closing files using C programming functions.
Which header file is used for File Handling in C?
The standard <stdio.h> header provides the main file-handling functions.
What is a file pointer?
A file pointer is a pointer of type FILE * used to access and perform operations on an opened file.
Example:
FILE *fp;
What is the use of fopen()?
fopen() opens an existing file or creates a file depending on the selected mode.
What is the use of fclose()?
fclose() closes an opened file and releases associated resources.
What is the difference between r, w, and a modes?
r→ Read an existing filew→ Write to a file and potentially overwrite existing contentsa→ Add data at the end of a file
What is random access in C?
Random access allows the file position indicator to be moved to a specific location using functions such as fseek().
Which functions are used for random file access?
The main functions are:
fseek()
ftell()
rewind()
Conclusion:
File Handling in C is an essential concept for storing and managing data beyond the lifetime of a program. With functions such as fopen(), fclose(), fgetc(), fputc(), fprintf(), fscanf(), fseek(), ftell(), and rewind(), you can create practical programs that work with persistent data.
Once you understand file modes, file pointers, text and binary files, sequential access, and random access, you can build more practical C applications such as student management systems, billing programs, employee records, and inventory systems.

Mujtaba Ansari is a Software Engineer, Founder & CEO of The Tech Earth. He writes about technology, AI, software, cybersecurity, blogging, Health tech, Agri Tech and digital trends to help readers stay updated with the latest innovations.
