For working professionals
For fresh graduates
More
5. Array in C
13. Boolean in C
18. Operators in C
33. Comments in C
38. Constants in C
41. Data Types in C
49. Double In C
58. For Loop in C
60. Functions in C
70. Identifiers in C
81. Linked list in C
83. Macros in C
86. Nested Loop in C
97. Pseudo-Code In C
100. Recursion in C
103. Square Root in C
104. Stack in C
106. Static function in C
107. Stdio.h in C
108. Storage Classes in C
109. strcat() in C
110. Strcmp in C
111. Strcpy in C
114. String Length in C
115. String Pointer in C
116. strlen() in C
117. Structures in C
119. Switch Case in C
120. C Ternary Operator
121. Tokens in C
125. Type Casting in C
126. Types of Error in C
127. Unary Operator in C
128. Use of C Language
When working with any programming language, dealing with external data storage is almost inevitable. Whether you're saving user input, logging application data, or reading configuration settings, you need to manage files effectively. That's where file handling in C becomes essential.
In this blog, we’ll explore file handling in C in detail. From the basics to advanced binary file operations, this guide will walk you through every major operation involved. Whether you’re a beginner aiming to understand the core concepts or a developer brushing up on skills, this blog is structured to help you gain clarity on file handling in C with easy-to-follow code examples, clear explanations, and practical use cases. It’ll also help you build foundation for a professional software development course.
We’ll not only cover how to create, open, write, and read files but also dive into handling binary files and using auxiliary functions to streamline file operations. But, before you begin, it’s recommended to learn about functions in C, as we’re going to use them for file handling in C. So, let’s start this journey and master the essentials of file handling in C, a must-have skill for any serious C programmer.
Imagine creating a program that takes hours of input from a user, performs complex calculations, and then poof, it’s gone when you close the terminal. Without file handling, C programs can only interact with the user during runtime, and all data vanishes once the execution ends.
This is why file handling in C is so crucial. It allows your program to store data permanently by writing to files and retrieve it later by reading from them. Whether you're building a student record management system, a logging mechanism, or a simple note-taking tool, file handling in C ensures your data lives beyond a single run of the program.
Build a future-forward career with the following full-stack development courses:
Here’s why file handling in C is indispensable:
In essence, file handling in C bridges the gap between volatile memory and permanent storage. It allows you to build robust applications that interact with the real world, where data isn't just temporary. To understand the memory aspect, you should explore our article on dynamic memory allocation in C.
Before diving into the mechanics of file handling in C, it's essential to understand the different types of files that the C language can work with. The type of file you choose affects not just how data is stored, but also how it's read and written. In C, files are generally categorized into two main types:
Text files store data as a sequence of characters. These characters are encoded using standard encodings like ASCII or UTF-8 and are human-readable. You can open and edit these files with any basic text editor such as Notepad, Vim, or Visual Studio Code.
Key Characteristics of Text Files:
Use Cases:
Binary files store data in the exact format as it is represented in memory, meaning it includes raw bytes. This makes binary files unreadable in a standard text editor, but much more efficient for complex data operations.
Key Characteristics of Binary Files:
Use Cases:
Also read, Header files in C to develop high-efficient C programs.
File handling in C revolves around a sequence of operations that allow you to interact with external files efficiently and safely. These operations are essential whether you're working with small config files or large binary datasets. Each operation is performed using specific standard library functions in C declared in <stdio.h>.
Below is a complete list of file handling operations in C, with a concise explanation and relevant functions.
Operation | Function(s) | Purpose |
Open a File | fopen() | Opens a file in the specified mode (read, write, append, etc.) |
Create a File | fopen() with "w" or "wb" mode | Creates a new file or overwrites if it already exists |
Read from a File | fgetc(), fgets(), fread(), fscanf() | Reads data from the file (character, line, formatted, or binary) |
Write to a File | fputc(), fputs(), fwrite(), fprintf() | Writes data to the file (character, line, formatted, or binary) |
Close a File | fclose() | Closes the file and flushes any buffered output |
Move File Pointer | fseek(), ftell(), rewind() | Manipulates or queries the current position in the file |
Binary Operation | Function(s) | Purpose |
Read Binary Data | fread() | Reads blocks of memory (raw binary data) from a file |
Write Binary Data | fwrite() | Writes blocks of memory (raw binary data) to a file |
Operation | Function(s) | Purpose |
Check for End of File | feof() | Returns true if the end-of-file indicator is set |
Check for File Errors | ferror() | Checks if an error occurred during file operations |
Clear Errors | clearerr() | Resets error indicators for a file stream |
Operation | Function(s) | Purpose |
Flush Output Buffer | fflush() | Forces a write of buffered output to the file |
This full suite of operations equips you to implement any level of file handling in C—from simple reading and writing to robust binary data processing. In the upcoming sections, each of these operations will be demonstrated with clean, commented code, outputs, and explanations.
Additionally, learn about the different types of functions in C, such as:
Opening a file is the first step in using file handling in C. This is done using the fopen() function, which opens a file and returns a pointer of type FILE*. You must specify the file name and the mode in which you want to open it.
Syntax of fopen()
FILE *fopen(const char *filename, const char *mode);
Here’s a complete table of file modes used in file handling in C:
Mode | File Type | Operation | Behavior |
"r" | Text | Read | Opens an existing file for reading. File must exist. |
"w" | Text | Write | Creates a new file or overwrites existing. Used for writing. |
"a" | Text | Append | Opens or creates a file for appending data at the end. |
"r+" | Text | Read + Write | Opens existing file for both reading and writing. File must exist. |
"w+" | Text | Read + Write | Creates or overwrites a file for reading and writing. |
"a+" | Text | Read + Append | Opens or creates a file for reading and appending. |
"rb" | Binary | Read | Opens existing binary file for reading. File must exist. |
"wb" | Binary | Write | Creates a new binary file or overwrites existing. |
"ab" | Binary | Append | Opens or creates binary file for appending data. |
"rb+" | Binary | Read + Write | Opens existing binary file for both reading and writing. File must exist. |
"wb+" | Binary | Read + Write | Creates or overwrites binary file for both reading and writing. |
"ab+" | Binary | Read + Append | Opens or creates binary file for reading and appending. |
Example: Opening a File in Different Modes
Here’s a simple demonstration of file handling in C using multiple modes:
#include <stdio.h>
int main() {
FILE *f1, *f2, *f3;
// Open for reading (must exist)
f1 = fopen("input.txt", "r");
// Open for writing (creates or overwrites)
f2 = fopen("output.txt", "w");
// Open for appending (creates if not exists)
f3 = fopen("log.txt", "a");
if (f1 == NULL || f2 == NULL || f3 == NULL) {
printf("Error opening one or more files.\n");
} else {
printf("All files opened successfully.\n");
}
// Always close opened files
if (f1) fclose(f1);
if (f2) fclose(f2);
if (f3) fclose(f3);
return 0;
}
Output
All files opened successfully.
(If files are accessible; otherwise an error message appears.)
Explanation
This overview gives you full visibility into every available mode for file handling in C, ensuring you choose the right one based on your specific task—whether reading a config file or writing binary logs.
Creating a file is one of the core tasks in file handling in C, and it’s typically accomplished using the `fopen()` function with write (`"w"` or `"wb"`) or append (`"a"` or `"ab"`) modes. These modes not only open the file but create it if it doesn’t already exist.
Using `"w"` or `"wb"` mode will create a new file or overwrite an existing one, while `"a"` or `"ab"` will create the file if it doesn’t exist, but append data to it if it does.
Let’s create a simple text file named `"newfile.txt"`.
#include <stdio.h>
int main() {
FILE *file;
// Open the file in write mode; creates it if it doesn't exist
file = fopen("newfile.txt", "w");
if (file == NULL) {
printf("Failed to create the file.\n");
} else {
printf("File created successfully.\n");
// Optional: Write a welcome message
fprintf(file, "Welcome to file handling in C.\n");
// Close the file
fclose(file);
}
return 0;
}
Output
File created successfully.
(And a line written inside the file: "Welcome to file handling in C.")
Explanation
To run your C programs on Mac or Linux operating systems, explore the following articles:
If you want to create a file to store binary data, just use `"wb"` instead:
FILE *binFile = fopen("data.bin", "wb");
This tells the system that the file will be used for binary output.
Creating files is a critical starting point for writing persistent data to the disk. In file handling in C, once a file is created, you can proceed to write structured or unstructured data into it.
Once you’ve successfully opened a file, writing data to it is a common task. There are different ways to write to a file depending on the format and type of data. Below, we will cover two popular methods for writing data: writing characters and writing formatted text.
Here’s a table summarizing the functions used for writing to a file:
Function | Description | Use Case |
fputc() | Writes a single character to a file. | Use when writing individual characters. |
fputs() | Writes a string (null-terminated) to a file. | Use when writing a string of characters. |
fprintf() | Writes formatted data to a file (similar to printf). | Use when writing formatted text (e.g., integers, floats, strings). |
fwrite() | Writes binary data (raw memory) to a file. | Use for writing binary data (arrays, structs, etc.). |
fputs() | Writes a string to a file without formatting. | Use when you need to write a simple string. |
fwrite() | Writes raw binary data to a file. | Write arrays, structs, or any binary data to a file. |
fputwc() | Writes a wide character to a file. | Use when working with wide characters. |
fwprintf() | Writes formatted wide characters to a file. | Use when writing formatted wide characters (for wide-character sets). |
Let’s begin with a simple example of writing a single character to a file using `fputc()`.
#include <stdio.h>
int main() {
FILE *file;
// Open the file in write mode (creates if not exists)
file = fopen("charfile.txt", "w");
if (file == NULL) {
printf("Failed to open the file.\n");
} else {
// Write a single character to the file
fputc('A', file);
printf("Character written successfully.\n");
// Close the file
fclose(file);
}
return 0;
}
Output
Character written successfully.
(The file "charfile.txt" will contain the character "A".)
Explanation
Also read, binary to decimal in C to strengthen your foundational knowledge.
For writing formatted text, we can use `fprintf()`. This is similar to `printf()` but instead of printing to the console, it writes to a file.
#include <stdio.h>
int main() {
FILE *file;
// Open the file in write mode
file = fopen("formattedfile.txt", "w");
if (file == NULL) {
printf("Failed to open the file.\n");
} else {
// Write formatted data to the file
fprintf(file, "Age: %d\nName: %s\n", 25, "Rahul Kumar");
printf("Formatted data written successfully.\n");
// Close the file
fclose(file);
}
return 0;
}
Output
Formatted data written successfully.
(The file "formattedfile.txt" will contain the following content:)
Age: 25
Name: Rahul Kumar
Explanation
When writing to a file in file handling in C, you can choose from different functions depending on the data format:
Each of these methods allows you to tailor your file operations to the data you're working with, whether that’s simple text, structured data, or raw binary information.
Reading data from a file is an essential operation in file handling in C. Depending on the type of data you're dealing with, C provides various functions to read files efficiently.
Here’s a table summarizing the functions used for reading from a file:
Function | Description | Use Case |
fgetc() | Reads a single character from a file. | Use when reading individual characters. |
fgets() | Reads a string (up to a specified limit) from a file. | Use when reading strings or lines of text. |
fscanf() | Reads formatted data from a file (similar to scanf). | Use when reading formatted data (e.g., integers, floats, strings). |
fread() | Reads binary data (raw memory) from a file. | Use for reading binary data (arrays, structs, etc.). |
fgetwc() | Reads a wide character from a file. | Use when working with wide characters. |
fwscanf() | Reads formatted wide characters from a file. | Use when reading formatted wide characters. |
In this example, we’ll use fgets() to read a line (or string) from a file. fgets() reads up to a specified limit and stores the result in a buffer.
#include <stdio.h>
int main() {
FILE *file;
char buffer[255];
// Open the file in read mode
file = fopen("stringfile.txt", "r");
if (file == NULL) {
printf("Failed to open the file.\n");
} else {
// Read a line (string) from the file
fgets(buffer, 255, file);
printf("String read: %s\n", buffer);
// Close the file
fclose(file);
}
return 0;
}
Output
String read: This is a sample string written to the file.
(The program reads the first line from the file "stringfile.txt" and displays it.)
Explanation
After performing read or write operations on a file in file handling in C, it is important to properly close the file to ensure that all data is written to the file (if applicable) and to free up system resources.
In C, closing a file is done using the `fclose()` function. This function ensures that the file is properly closed and no further operations can be performed on it.
1. Data Integrity: Closing a file ensures that all data is written from memory (buffer) to the disk, making the file's contents consistent.
2. Freeing Resources: Files consume system resources. By closing them, you free up the memory and file handles, avoiding resource leaks.
3. Preventing Data Loss: If a file is not closed properly, there might be a risk of losing data, especially if you were writing to the file. Data in the buffer may not be written to the file until the file is closed.
Let’s use a simple example to demonstrate how to close a file after reading or writing data. Here, we will open a file, perform some operations (writing data), and then close the file.
#include <stdio.h>
int main() {
FILE *file;
// Open the file in write mode
file = fopen("example.txt", "w");
if (file == NULL) {
printf("Failed to open the file.\n");
} else {
// Write data to the file
fprintf(file, "Hello, world!\n");
// Close the file after writing
fclose(file);
printf("File written and closed successfully.\n");
}
return 0;
}
Output
File written and closed successfully.
(The file "example.txt" will contain the text: `Hello, world!`.)
Explanation
In file handling in C, the file pointer is used to keep track of the current location in the file where read and write operations occur. By default, when you open a file for reading or writing, the file pointer is positioned at the beginning of the file. However, you may need to move the file pointer to different positions within the file during the file operations.
C provides several functions to move the file pointer to a desired position. These functions allow you to:
1. Seek a specific position within the file.
2. Reset the file pointer back to the beginning or to the end.
3. Move the pointer relative to a specific reference point (e.g., from the beginning, the current position, or the end).
The functions used to move the file pointer are:
The `fseek()` function is used to move the file pointer to a specific location within the file. It allows for both absolute and relative positioning.
Syntax:
int fseek(FILE *file, long int offset, int whence);
The `ftell()` function returns the current position of the file pointer within the file.
Syntax:
long ftell(FILE *file);
The `rewind()` function is used to reset the file pointer back to the beginning of the file. It is equivalent to calling `fseek()` with `SEEK_SET` and an offset of `0`.
Syntax:
void rewind(FILE *file);
`file`: Pointer to the file.
In this example, we will demonstrate how to move the file pointer using `fseek()`, `ftell()`, and `rewind()`.
#include <stdio.h>
int main() {
FILE *file;
char buffer[255];
// Open the file in write mode
file = fopen("example.txt", "w");
if (file == NULL) {
printf("Failed to open the file.\n");
} else {
// Write some data to the file
fprintf(file, "This is the first line.\n");
fprintf(file, "This is the second line.\n");
// Move the file pointer to the beginning of the file
rewind(file);
// Read and print the first line
fgets(buffer, 255, file);
printf("First line: %s", buffer);
// Move the file pointer to 10 bytes from the beginning
fseek(file, 10, SEEK_SET);
// Read and print the second line starting from the 10th byte
fgets(buffer, 255, file);
printf("Second line after moving pointer: %s", buffer);
// Close the file
fclose(file);
}
return 0;
}
Output
First line: This is the first line.
Second line after moving pointer: is the second line.
Explanation
In file handling in C, binary files are different from text files. A binary file contains raw data in its original format, as opposed to text files which store characters as human-readable text. In binary files, data is stored in a format that’s suitable for efficient reading and writing.
When working with binary files in C, we use `fread()` and `fwrite()` functions to read and write data in its raw form. These functions allow you to read and write complex data types like arrays and structs, unlike text files that treat data as strings or characters.
Functions for Reading and Writing Binary Data
The `fwrite()` function is used to write data to a binary file. It writes data in blocks, and its syntax is as follows:
Syntax:
size_t fwrite(const void *ptr, size_t size, size_t count, FILE *file);
It returns the number of elements successfully written, or `0` if an error occurred.
The `fread()` function is used to read binary data from a file into a buffer. Its syntax is as follows:
Syntax:
size_t fread(void *ptr, size_t size, size_t count, FILE *file);
It returns the number of elements successfully read, or `0` if an error occurred.
In this example, we will demonstrate how to write and read an array of integers to and from a binary file.
#include <stdio.h>
int main() {
FILE *file;
int numbers[5] = {1, 2, 3, 4, 5};
// Writing binary data to a file
file = fopen("binaryfile.bin", "wb"); // Open in write-binary mode
if (file == NULL) {
printf("Failed to open the file.\n");
return 1;
}
// Write the array of integers to the binary file
fwrite(numbers, sizeof(int), 5, file);
printf("Data written to binary file successfully.\n");
// Close the file after writing
fclose(file);
// Reading binary data from the file
file = fopen("binaryfile.bin", "rb"); // Open in read-binary mode
if (file == NULL) {
printf("Failed to open the file for reading.\n");
return 1;
}
// Read the data into a new array
int readNumbers[5];
fread(readNumbers, sizeof(int), 5, file);
printf("Data read from binary file:\n");
// Print the read data
for (int i = 0; i < 5; i++) {
printf("%d ", readNumbers[i]);
}
printf("\n");
// Close the file after reading
fclose(file);
return 0;
}
Output
Data written to binary file successfully.
Data read from binary file:
1 2 3 4 5
Explanation
1. Writing to a Binary File:
2. Reading from a Binary File:
In file handling in C, apart from the basic file operations such as opening, reading, writing, and closing files, there are several additional functions that help manage and manipulate files efficiently. These functions provide more control and functionality when working with files, whether for error handling, checking file status, or manipulating file attributes.
Here’s a look at some of the important additional functions used in file handling in C:
Function | Description | Syntax | Return Value |
remove() | Deletes a file from the filesystem. | int remove(const char *filename); | 0 on success, -1 on error |
rename() | Renames or moves a file. | int rename(const char *oldname, const char *newname); | 0 on success, -1 on error |
fflush() | Flushes the output buffer of a stream to the file. | int fflush(FILE *stream); | 0 on success, EOF on error |
ferror() | Checks for errors on the last file operation. | int ferror(FILE *stream); | Non-zero if error, 0 if no error |
feof() | Checks if the end of the file has been reached. | int feof(FILE *stream); | Non-zero if EOF, 0 otherwise |
ftell() | Returns the current position of the file pointer. | long ftell(FILE *stream); | Current position (byte offset) |
rewind() | Resets the file pointer to the beginning of the file. | void rewind(FILE *stream); | None |
In file handling in C, understanding how to properly open, read, write, and close files is essential for managing data efficiently. By using the right file modes and operations like fopen(), fread(), fwrite(), and fclose(), you can perform a wide range of tasks with both text and binary files. Mastering these basic functions is crucial for working with persistent data, from simple applications to more complex programs.
Additionally, advanced functions such as remove(), rename(), and fflush() provide more control over file management, helping ensure data integrity and smooth file operations. Whether you're dealing with user data or large datasets, file handling in C is an indispensable skill for any programmer. With this guide, you're well-equipped to manage files effectively in your C programs.
File handling in C enables programs to perform tasks such as saving, loading, and modifying data stored in files. Instead of hardcoding data, file handling allows C programs to interact with external data files, making programs more dynamic and capable of handling larger datasets. It is essential for tasks like logging, configuration settings, and persistent data storage.
To open a file for writing in C, use the fopen() function with the mode "w". This mode opens the file for writing, and if the file doesn't already exist, it will be created. If the file exists, its contents will be overwritten. Ensure to handle cases where the file cannot be opened by checking if the file pointer is NULL.
The "r" mode in file handling opens a file for reading only, and the file must exist. If the file does not exist, fopen() returns NULL. The "w" mode opens a file for writing, and if the file doesn't exist, it creates one. However, if the file exists, it overwrites the current contents of the file.
Yes, you can read and write to the same file in C using the "r+" or "w+" modes. The "r+" mode allows both reading and writing, but the file must exist. The "w+" mode opens the file for both reading and writing, but it will overwrite the file if it already exists. Use the correct mode depending on your use case.
To append data to an existing file in C, use the "a" mode when opening the file with fopen(). This mode opens the file for writing, but it does not overwrite the existing contents. Any data written to the file will be added to the end. It is useful when you want to add new data without altering the file’s existing content.
File handling in C is more low-level compared to many higher-level programming languages. In C, you have direct control over file operations using functions like fopen(), fread(), fwrite(), and fclose(). While higher-level languages abstract file operations to simplify the process, C provides more control and requires developers to manage things like file pointer positions and memory explicitly.
The file pointer in C is crucial for file operations, as it keeps track of the current position in the file where read or write operations will occur. The file pointer starts at the beginning of the file when opened and can be moved using functions like fseek(). It ensures that data is read or written in the correct sequence and position.
In C, to check if you’ve reached the end of a file, you can use the feof() function. It returns a non-zero value when the end of the file is reached. It is commonly used after read operations to ensure that all content has been processed. However, avoid relying solely on feof() to control file reading.
Binary files store data in its raw, machine-readable form, unlike text files, which store human-readable characters. In C, binary files are handled using functions like fread() and fwrite() to read and write data in raw form. Binary files allow efficient storage of complex data types, such as structures and arrays, without conversion to text format.
To read an entire file in C, you can use the fread() function in combination with a loop to read data into a buffer. Alternatively, if the file is a text file, fgets() can be used to read line by line. You can also use fseek() to ensure that the file pointer moves to the correct position for sequential reading.
Forgetting to close a file in C using fclose() can result in data not being properly written to the file, as buffered data may not be flushed. Additionally, leaving files open consumes system resources, which could lead to memory leaks or file locking issues. It is essential to always close files after operations are done to prevent such problems.
Take a Free C Programming Quiz
Answer quick questions and assess your C programming knowledge
Author|900 articles published
Previous
Next
Start Learning For Free
Explore Our Free Software Tutorials and Elevate your Career.
Talk to our experts. We are available 7 days a week, 9 AM to 12 AM (midnight)
Indian Nationals
1800 210 2020
Foreign Nationals
+918068792934
1.The above statistics depend on various factors and individual results may vary. Past performance is no guarantee of future results.
2.The student assumes full responsibility for all expenses associated with visas, travel, & related costs. upGrad does not provide any a.