File Handling In C Programming [Explained With Examples]
The concept of File Handling is very important in C language. To understand the concept of file handling, first of all, you need to understand about what are the files and what are the types of files.
So without wasting any time let’s understand what is a file.
What is a file?
A file is a collection of bytes that is stored on a secondary storage device such as a disk. There are two types of files in a system:
- text file
- binary file
1) Text File -:
Text files are normal .txt files. Creating these text files is very easy. You can easily create these text files using any simple text editor like Notepad
When you open these text files, you will see all the contents of the file as plain text. If you want, you can easily edit or delete these content.
2) Binary Files -:
You have seen some file named .bin on your computer. This .bin file is called a binary file.
Instead of storing information in plain text, binary files store information in the form of binary numbers (0 and 1).
We can store a large amount of data in these binary files. Since the information in these binary files is in binary form (in the form of 0’s and 1’s), they cannot be read easily. These are not readable.
So friends, till now we have known what are files and how many types of files are there.
Let us now understand what is file handling In C and why file handling is needed.
What is File Handling In C
In C language, any variable gets memory when the program comes in RAM. Since the program gets memory in RAM and RAM is a volatile memory, all the program’s data is destroyed when the program goes out of RAM.
As soon as the program exits the RAM, the memory space assigned to the variable is also deallocated.
In such a situation, if we want to keep the store value in these variables as a permanent store, then we will not be able to keep it because the life of the variable is at most equal to the life of the program, when the program ends, the variables also expire.
If we want to store values in variables even after the program ends, then for this we have to store the stored values in these variables in permanent storage memory (such as files inside hard disk).
To do this, we have to write some such code in our program so that the data inside the variable is saved inside the file located in the secondary storage and when we do this, then it is known as file handling.
File handling is a way in which we can store the program’s data in disk files permanently.
Through file handling, we can easily store the program’s data located inside the variables in the secondary storage inside the files and we can re-use the data inside these files by assigning them to the variables.
Through file handling in C language, we can easily create, update, read, and delete files.
File handling can be mainly divided into categories -:
- High level (standard files or stream oriented files)
- Low-level (system oriented files)
High-level file handling is managed by library functions and low-level file handling is managed by system calls.
High level file handling is commonly used because it is easier to manage.
For file handling, we have to use many file functions and operations in our program.
Let’s know about those file functions and operations.
Functions use in File Handling
Function | description |
fopen() | To create a new file or open an already created file. |
fclose() | To close the file. |
getc() | To read character from file. |
putc() | To write character in file. |
fscanf() | To read set of data from file. |
fprintf() | To write the set off data to the file. |
getw() | To read integers from a file. |
putw() | To write an integer in a file |
fseek() | To set the position to the desired point. |
ftell() | To provide the current position in the file. |
rewind() | To set the position to the beginning of the file. |
All the functions that I have mentioned above, all the functions used in file handling, which we are going to use while creating the program below.
It may happen that you do not understand the use of these functions well yet, but when we read about file handling in the future, then you will be well aware of all these functions.
If you want a separate article about the use of these functions, then tell me in the comment below, if more people’s comments come, then I will tell about these functions by writing separate articles.
Let’s now understand about some file operations.
File Operations
In C language, we perform the following types of file operations –
- Creation of a new file
- Opening an existing file
- Reading from file
- Writing to a file
- Moving to a specific location in a file
- Closing a file
Opening or Creation of a new file
The fopen() function is used to create files or open created files in C language. The fopen() function is defined in a header file named stdio.h . Its syntax is something like this –
Syntax -:
FILE *fp;
fp = fopen("file_name","mode");
- Here fp is a FILE pointer that will point to the file to be opened by fopen().
- FILE is a structure that contains information related to the file such as name, size, buffer size, current position, end of file, etc.
- file_name – Here the name of the file that we want to open will come.
- Mode – We decide the mode according to which operation (like read, write, update) we want to do in the file.
Example -:
FILE *fp;
fp = fopen("fileName.txt", "w")
Here in this example, fileName.txt is the name of the file we want to open and w is the file opening mode which indicates that we are opening this file to perform the write operation.
In C language, we have different file opening modes according to different conditions, which have their own purpose, let’s know about these opening modes.
File Opening Modes In C
Mode | Description |
r | opens a text file in read mode |
w | opens a text file in write mode |
a | opens a text file in append mode |
r+ | opens a text file in read and write mode |
w+ | opens a text file in read and write mode |
a+ | opens a text file in read and write mode |
rb | opens a binary file in read mode |
wb | opens a binary file in write mode |
ab | opens a binary file in append mode |
rb+ | opens a binary file in read and write mode |
wb+ | opens a binary file in read and write mode |
ab+ | opens a binary file in read and write mode |
So friends these are some file opening modes that we use with fopen() function.
To know more about these file opening modes, you must watch the video given below once because to understand what I am going to tell you next, you need to know about the file opening mode well.
How fopen() function works
Whenever we call the fopen() function, it first finds the file that you wrote in the parenthesis of the fopne() function in your computer disk.
If the fopen() function finds that file, it loads this file from disk into the buffer space, and then opens the file from the buffer in required mode, and if the file is not found, it automatically creates a new file. gives and opens it. It names this new file the same as you did in its parenthesis.
Let’s understand the use of fopen() function with an example.
Example -:
#include <stdio.h>
int main()
{
FILE * fp;
if (fp = fopen("hello.txt", "r"))
{
printf("File opened successfully in read mode");
}
else
printf("The file is not present! cannot create a new file using r mode");
fclose(fp);
return 0;
}
Output -:
The file is not present! cannot create a new file using r mode
Program explanation -:
In this program, we first created a file pointer named fp which points to the file to be opened by the fopen() function.
With the fopen() function, we tried to open the file in read mode, but the file was not opened because there was no file with this name in our disk, so the file was not opened and the else statement in the result was run.
If we opened this file in write mode, then a new file would have been created and opened. But in read mode, a file is opened only if it is already present in our disk but in this program, there was no file with this name in our disk so the new file was not created.
At the end of the program, we close the file using the fclose() function.
Closing a File
As I told you above, fclose() function is used to close any file. Through fclose() we can easily close any file.
Although in C language, the files are closed with the end of the program, but I would advise you to close the file manually using the fclose() function. It would be a good practice for you to do this.
Syntax -:
fclose(file_pointer);
Reading from file
To read a file, first of all, that file has to be opened in read mode “r” by fopen() function.
After opening the file, we use some functions in C language to read the data inside the file.
- fgetc()
- fgets()
- fscanf()
1. fgetc(file_pointer) -: It returns the next character from the file pointed to by the file pointer. This function returns EOF (End of File) when it reaches the end of the file.
Example -:
#include <stdio.h>
#include <stdlib.h>
int main()
{
/* Pointer to the file */
FILE *fp1;
/* Character variable to read the content of file */
char c;
/* Opening a file in r mode*/
fp1= fopen ("C:\\myprogram.txt", "r");
/* Infinite loop –I have used break to come out of the loop*/
while(1)
{
c = fgetc(fp1);
if(c==EOF)
break;
else
printf("%c", c);
}
fclose(fp1);
return 0;
}
2. fgets() -: It reads n-1 characters from the file and stores the string in a buffer with the NULL character ‘\0’ appended as the last character.
Syntax -:
fgets(buffer, n, file_pointer);
3. fscanf() -: It is used to analyze the data. It reads characters from the file.
Like the scanf function, it stops reading when space or newline is entered.
Syntax -:
fscanf(file_pointer, conversion_specifiers, variable_addresses);
Example -:
FILE *fp
fp = fopen (“file.txt”, “r”);
fscanf (fp, "%s %s %s %d", str1, str2, str3, &date);
Writing to a file
To perform the writing operation inside the file, first you have to open that file in write mode “w”.
If you open the file in any other mode such as “r” mode, then you cannot perform the writing operation in the file. If you try to do so, the compiler will give you an error.
Opening the file in write mode “w” will delete the data written from it and enter the newly entered data into the file.
After the file is opened, the fprintf, fputc and fputs functions are used to write in the file.
The work of these three functions is the same, it depends on you which one you use.
Example -:
Here I am showing you how to perform write operation to a file using fprinf function:
#include <stdio.h>
#include <stdlib.h>
int main()
{
char ch;
FILE *fp;
fp = fopen("C:\\myprogram.txt","w");
if(fp == NULL)
{
printf("Error");
exit(1);
}
printf("Enter any character: ");
scanf("%c",&ch);
/* You can also use fputc(ch, fp);*/
fprintf(fp,"%c",ch);
fclose(fp);
return 0;
}
Conclusion
Friends, I hope you have found the answer to your question and you will not have to search about what is file handling In C and why file handling is Important.
However, if you want any information related to this post or related to programming language, or computer science, then comment below I will clear your all doubts
If you want a complete tutorial on C language, then see here C Language Tutorial. Here you will get all the topics of C Programming Tutorial step by step.
Friends, if you liked this post, then definitely share this post with your friends so that they can get information about file handling In C
To get the information related to Programming Language, Coding, C, C ++, subscribe to our website newsletter. So that you will get information about our upcoming new posts soon.
thank you jeetu mama