File Handling in C
Learn via video course

Abstract
File handling in C stores data of our program in our local store, which can be used at any time because as the execution of a program completes, our data is lost. Therefore, we need to save our data in any file form - text or binary files.
We can perform tasks like opening, reading the existing file, writing or adding new content, creating a new file, closing the file, or even saving the file to a certain location using C.
Scope of Article
- This article uses examples to open, read, write, create, and delete a file. As well as we will be looking at different types of files in C - text and binary.
- This article does not compare file handling in C with any other programming language.
Introduction
In programming, we may need a specific piece of input data to be created multiple times. It is not always sufficient to display data on the console. The data to be displayed may be large, and only a limited amount of data may be displayed on the console. As the memory is volatile, it is inefficient to compute the same programmatically created data repeatedly. If we need to save something, we can do so on the local file system, which is non-volatile and accessible at any time. This necessitates the use of file management in C.
So, what is file handling in C? A file is a method of permanently storing data in a series of bytes on a disc. The contents of a file are not as volatile as the memory of a C compiler. When declaring a file in C, the structure pointer of the file type is used.
The need for file handling in C is because -
- It saves time as we can easily access any part/outcome of the code whenever required.
- It helps in preserving the data or information for reusability.
- There is no need to worry about storage.
- And without data loss, we can easily transfer the contents of a file.
The data is saved as a file which can be a text or a binary file. Let’s see them in detail one by one.
Types of Files in C
We will be working with two types of files: -
- Text file
- Binary file
Let’s understand them in brief -
Text file - The user can create these files easily while handling files in C. It stores information in the form of ASCII characters internally, and when the file is opened, the content is readable by humans. It can be created by any text editor with a .txt or .rtf (rich text)extension. Since text files are simple, they can be edited by any text editor like Microsoft Word, Notepad, Apple Text Edit, etc.
Binary file - It stores information in the form of 0’s or 1’s, and it is saved with the .bin extension, taking less space. Since it is stored in a binary number system format, it is not readable by humans. Therefore it is more secure than a text file.
File Handling Functions in C
Now, we will be talking about different file-handling functions.
Function | Description | Syntax |
---|---|---|
fopen() | Used to open an existing file or to create a new file | FILE *fopen(“file_name”, “mode”); |
fprintf() | Used to write data in existing file | fprintf(FILE *stream, const char *format [, argument, ...]) |
fscanf() | Used to read data from the file | fscanf(FILE *stream, const char *format [, argument, ...]) |
fputc() | Used to write characters in a file | fputc(int c, FILE *stream) |
fgetc() | Used to read characters from a file | fgetc(FILE *stream) |
fclose() | Used to close existing file | fclose( FILE *fp ) |
fseek() | puts the file pointer to the specified place | fseek(FILE *stream, long int offset, int whence) |
fputw() | Used to write integral value in the file | fputw(int number,File *fp) |
fgetw() | Used to read integral value from the file | fgetw(File *fp) |
ftell() | It will return the current position of the file pointer in the file | ftell(FILE *stream) |
rewind() | the file pointer is set to the start of the file | rewind(FILE *stream) |
Modes to Open a File in C
We use fopen() with different opening modes to open a file. The most common modes used are listed below.
Mode | Description | Example |
---|---|---|
r | opens a text file in read-only mode | fopen(“demo.txt”, “r”) |
w | opens a text file in the write-only mode | fopen(“demo.txt”, “w”) |
a | opens a text file in append mode | fopen(“demo.txt”, “a”) |
r+ | opens a text file in read and write mode | fopen(“demo.txt”, “r+”) |
w+ | opens a text file in read and write modes | fopen(“demo.txt”, “w+”) |
a+ | opens a text file in read and write modes | fopen(“demo.txt”, “a+”) |
rb | opens a binary file in read mode. | fopen(“demo.txt”, “rb”) |
wb | opens a binary file in write mode. | fopen(“demo.txt”, “wb”) |
ab | opens a binary file in append mode | fopen(“demo.txt”, “ab”) |
rb+ | opens a binary file in read and write modes | fopen(“demo.txt”, “rb+”) |
wb+ | opens a binary file in read and write modes | fopen(“demo.txt”, “wb+”) |
ab+ | opens a binary file in read and write modes | fopen(“demo.txt”, “ab+”) |
In append mode, we can write data into an existing file without deleting existing contents. In contrast, in write mode, existing data is deleted, which was already present in the file.
Operations to Open a File in C
There are different kinds of operations to open a file in C.
- Creating a new file
- Opening an existing file
- Writing data to a file
- Reading data from an existing file.
- Moving data to a specific location on the file
- Closing the file
Creating a new file
We use the fopen() function to create a new file and open an existing file in our storage.
The syntax of fopen()- fopen("filename","mode")
When declaring a file in C, the pointer of the file type (FILE) is used to point the file. fopen() will give the file address to the file pointer which is going to create/open.
Let's create a new file with the name file2.txt.
Example:
A new file will be created in the folder where your code is saved. You can also specify the path to your file's creation. file = fopen ("C://file2.txt", "w");
We use write mode because it will create a new file if the file is not present.
Opening an Existing File
We use fopen() with the required opening modes to open an existing file, as discussed. We have already created a file using write mode. In the following code, use r mode. That is, open the file in read mode.
Code:
Writing Data to a File
Let's write in the file that we created in the previous example. So to do that, I'll be using fprintf() to write a text in the file with the name file2.txt.
Code:
Output
As for the output, the data has been written in the existing file.
Reading Data From an Existing File
To read data from an existing file, we will use “r” mode in file opening. To read the file character by character, we use getc(). And to read line by line, we use fgets().
Example:
In the above program, getc() will read the file character by character until the end of the file(EOF) does not occur.
As file2.txt was already present in my directory, the output is as shown.
Output:
Moving Data to a Specific Location on the File
To put the file pointer to a specific place, we use fseek(). With the help of it, we can write data at whatever location we want in the file.
Syntax -
fseek(FILE stream, long int offset, int whence)
- file stream - pointer to the file. As in the example file, the pointer to the file object "myfile.txt".
- offset - This is the number of bytes that must be offset/skipped from whence.
- Hence take three values -
SEEK_SET - sets the pointer at the beginning of the file. SEEK_CUR - sets the pointer at the current position of the file SEEK_END - sets the pointer at the end of the file.
Let’s understand it with an example -
The text file is updated, as you can see in the output.
Output:
Initially, the output will be Welcome to khan Academy mate! But we had reset the right pointer at the 10th position from the beginning, i.e., W, and using the help of fputs(), the statement is overwritten. The final output is Welcome to Scaler Academy mate!
Closing the File
To close a file that is already open, we will use fclose(). As we have already discussed the syntax of it, we will directly head over to the example.
In this example, the file is the pointer associated with the file(file2.txt) which is to be closed. After closing the file, the file pointer lost the reference of the file and started pointing to NULL.
Conclusion
- Because data is destroyed after the program is finished, file handling allows you to preserve your data for later use.
- Different kinds of files - text (saved as .txt or .rtf) and binary(saved as .bin).
- Opening modes in file handling - read("r"), write("w") and append("a").
- Important File handling functions - fopen() - to open an existing file or create a new file fprintf() - to write characters in existing file fscanf() - to read characters from the file fclose() - used to close the file