File Handling in C
The C programming language has various features and functionalities which help in better and efficient coding. In the previous articles, we just compiled and ran the program but we didn’t save the output anywhere in the system.
But let’s say that you want to store the output for future uses. Then what should you do?
That’s when the file handling feature of C comes into play. You can store the output or data onto the local file system which is volatile and it can be accessed every time.
What is file handling in C?
A file is a container in computer storage devices which is used for storing output or information permanently in the form of a sequence of bytes on the disk.
In C, you can perform various file handling operations like creating a file, deleting a file, opening a file, reading a file or you can even manipulate the data inside of a file. You can also work with the data in your program code by fetching it from a file.
Need for file handling in C
Suppose, you want to check the output of some program several times, it will be a lazy task to compile and run the program every time. With the help of file handling, you can easily solve this problem.
- Reusability:- When a program is terminated, the data will be lost. You can store your data into a file even if the program terminates, you will not lose your data.
- Portability:- You can easily move the data of the file from one computer to another computer without any changes.
- Time-Saving:- Let’s say that you have a large number of data to enter. But it will cost you a lot of time to enter them all. You can easily overcome this problem by storing all the data into a file and later accessing them through a few commands in C.
- Large storage capacity:- With the help of files, you can store a large number of data into a file. You don’t have to worry about the storage capacity.
Types of Files in C
There are 2 types of data files present in C programming language:-
1. Text Files
You can easily read and use the text files. It is created with the .txt extension. Text files are always in human-readable format. You can read or edit the text file easily with the help of text editors like notepad etc. It consumes a large storage space. It does not provide any security to the data or information and stores the data or information in the form of ASCII characters.
2. Binary Files
It occupies less space and is created with the .bin extension. It stores data or information in the form of 0’s and 1’s. Binary files are not human-readable that’s why it is more secure than text files. It is the best way to store information or data in a data file. It is much easier to access.
File Handling Operations in C
You can perform various file handling operations in C. In C, we can use file handling functions for various types of file manipulation like create, update, read or delete the files on the local file system. Below are the operations that you can perform on a file:-
- Creating a new file.
- Opening an existing file.
- Reading from a file.
- Writing to a file.
- Deleting a file.
Functions for file handling in C
In C, you can make use of some functions which are used for file handling purposes. Below is the list of functions:-
Function | What it does |
fopen() | Used for opening a new or existing file. |
fprintf() | Used to write data into a file. |
fscanf() | Used to read data from a file. |
fputc() | Used to write a character into a file. |
fgetc() | Used for reading a character from a file. |
fclose() | Closes a file. |
fseek() | Used to set the file pointer to a given position. |
fputw() | Used to write an integer to a file. |
fgetw() | Used for reading an integer from a file. |
ftell() | Used to return a current position. |
rewind() | Used to set the file pointer at the beginning of a file. |
Working with files in C
Before working with the files, you have to declare a pointer of type file. It is needed for the communication between the program and the file.
FILE *fptr;
1. Opening or Creating a file in C
Before making changes to a file, you will have to open it first. You can use the fopen() function for that. You can also create a new file using the fopen() function.
Syntax of fopen():-
FILE *fopen( char *filename, char * mode );
fopen() function accepts two parameters:-
- filename:- Name of the file which you want to open or create. If it is stored at some specific location then you must provide the full path of the file.
- mode:- The mode in which you want to open the file.
Example:-
fopen("C:\\temp\\file.txt","w"); fopen("D:\\program.bin","rb");
In the above example, if the file.txt file does not exist in the location C:\\temp then it will create a new file called file.txt in that location. The mode ‘w’ lets you create or edit the contents of a file. The second one opens an existing file for reading in binary mode in the location D:\\. The ‘rb’ mode only allows you to read the file in binary mode. You cannot write into that file.
Below are some modes that you can use in fopen() function:-
Mode | What it does |
r | Used to open a text file in read mode |
w | Used to open a text file in write mode |
a | Used to open a text file in append mode |
r+ | Used to open a text file in read and write mode |
w+ | Used to open a text file in read and write mode |
a+ | Used to open a text file in read and write mode |
rb | Used for opening a binary file in read mode |
wb | Used for opening a binary file in write mode |
ab | Used for opening a binary file in append mode |
rb+ | Used for opening a binary file in read and write mode |
wb+ | Used for opening a binary file in read and write mode |
ab+ | Used for opening a binary file in read and write mode |
Working of fopen() function in C
- It first searches for the file at the given location.
- Then, it will load the file and place it into a buffer.
- Then, it sets up a character pointer and it points to the first character of that file.
Example of fopen() function
#include<stdio.h> int main( ) { FILE *file1; char s; file1 = fopen("1.c","w"); while ( 1 ) { s = fgetc(file1); if(s == EOF) break; printf("TechVidvan Tutorial: fopen() function!\n"); printf("%c",s) ; } fclose(file1) ; }
You get the content of the file as output.
In the above example, we opened a file in write mode.
2. Closing a file in C
In C, after the reading and modification of a file is done then you can close it with the fclose() function.
Syntax of fclose():-
fclose(filepointername);
- filepointername is a file pointer which is associated with the file.
Example:-
FILE *file_name ; file_name= fopen("file1.txt", "w"); // perform some file handling operations! fclose(file_name);
3. Reading and writing to a text file in C
First we have to know that there are 3 types of streams in a file such as:-
- Input
- Output
- Input/Output
a. Reading to a text file:-
You can use the fscanf() function to read from a file.
FILE *filepoint; filepoint = fopen("1.txt", "r"); fscanf(filepoint, "%d %s", num, str2);
b. Writing to a text file:-
You can use the fprintf() function to write to a file.
FILE *ptr ; ptr = fopen("2.txt", "w"); fprintf(ptr, "%s %s", "TechVidvan", "Tutorials!");
For purposes like reading and writing to a file, input/output operations will help you.
You can use functions such as fprintf(), fscanf() for reading and writing to a text file. The one and only difference between fprintf(), fscanf() and printf(), scanf() is that the fprintf(), fscanf() function expects a pointer to the structure FILE.
Example of Write to a text file using fprintf()
#include <stdio.h> #include <stdlib.h> int main() { int number; FILE *filename; filename = fopen("C:\\write.txt","w"); if(filename == NULL) { printf("Error!"); exit(1); } number = 10; printf("TechVidvan Tutorial: Writing to a text file!\n"); fprintf(filename,"%d",number); fclose(filename); return 0; }
If you compile and run the above example then it will create a file named write.txt in the C drive of your computer. And if you open the file, you can see that the number 10 is stored in the write.txt file.
Example to Read from a text file using fscanf()
#include <stdio.h> #include <stdlib.h> int main() { int number; FILE *filename; filename = fopen("C:\\write.txt","r"); if(filename == NULL) { printf("Error!"); exit(1); } fscanf(filename,"%d",&number); printf("TechVidvan Tutorial: Reading from a file!\n"); printf("Value stored in 'write.txt' is: %d",number); fclose(filename); return 0; }
If you run and compile the above example then it will read the value stored in write.txt file and print the value which is 10 in the computer screen.
You can also use functions like fgetc() and fputc() in a similar way.
Reading and writing to a binary file in C
You can also read and write to a binary file in C. In case of binary files, you can make use of functions like fread() and fwrite() for reading from and writing to a file on the disk.
a. Writing to a binary file:-
You have to use the fwrite() function to write to a binary file. The fwrite() function takes 4 arguments such as:-
- Address of data.
- Size of data.
- Number of such types of data.
- Pointer to the file.
Syntax:-
fwrite(address_of_Data, size_of_Data, data_number, file_pointer);
Example of Writing to a binary file using fwrite()
#include <stdio.h> #include <stdlib.h> struct put_two { int num1, num2; }; int main() { int i; struct put_two num; FILE *filename; filename = fopen("C:\\write_to_binary.bin","wb"); if(filename == NULL) { printf("Error!"); exit(1); } for(i = 1; i < 3; ++i) { num.num1 = i; num.num2 = 3*i; fwrite(&num, sizeof(struct put_two), 1, filename); } printf("TechVidvan Tutorial: Writing to a binary file!\n"); fclose(filename); return 0; }
In the above example, we have created a file called write_to_binary.bin in the C drive. We also declared a structure named put_two with two integers such as num1 and num2. We also defined it in the main function as num. After that inside the for loop, we stored the value into the file using the fwrite() function.
The first parameter of the fwrite() function takes the address of num and the second parameter takes the size of structure put_two. The third parameter is set to 1 because we are only inserting one instance. And the fourth parameter points to the file in which we are storing. Atlast, we close the file.
b. Reading from a binary file:-
You can use the fread() function to read data from a binary file in C. The fread() function also accepts 4 arguments like the fwrite() function.
Syntax:-
fread(address_of_Data, size_of_Data, data_number, file_pointer);
Example of Reading from a binary file using fread()
#include <stdio.h> #include <stdlib.h> struct put_two { int num1, num2; }; int main() { int i; struct put_two num; FILE *filename; filename = fopen("C:\\write_to_binary.bin","wb"); if(filename == NULL) { printf("Error!"); exit(1); } for(i = 1; i < 3; ++i) { fread(&num, sizeof(struct put_two), 1, filename); printf("Values are: %d\t %d\t", num.num1, num.num2); } fclose(filename); return 0; }
In the above example, you are reading from the same file called write_to_binary.bin. You will get the same results which you inserted in Example3 as the output.
Getting data using fseek() function:-
If you want to get the required data at a specific location then you can use the fseek() function in C. From the name. you can say that it seeks the cursor to the given record in the file.
Syntax:-
fseek(FILE *file_pointer, long int offset, int whence);
- The first parameter is the pointer to the file.
- The second parameter is the position of what you need to find.
- The third parameter determines the location from where the offset begins.
Different types of whence in fseek():-
- SEEK_SET:- Used to start the offset from the beginning of the file.
- SEEK_END:- Used to start the offset from the end of the file.
- SEEK_CUR:- Used to start the offset from the current location of the cursor in a file.
Example of fseek() function in C
#include <stdio.h> void main(){ FILE *filepoint; filepoint = fopen("2.txt","w+"); fputs("TechVidvan TutorialHi", filepoint); fseek(filepoint,18 , SEEK_SET); fputs(": Using fseek() in C!", filepoint); fclose(filepoint); }
2.txt
TechVidvan Tutorial: Using fseek() in C!
C fputc() and fgetc():-
Writing to a file:- fputc()
With the help of fputc() function, you can write a single character into a file.
Syntax:-
fputc(character, FILE *stream);
Example of fputc() function
#include <stdio.h> void main(){ FILE *filepoint; filepoint = fopen("3.txt", "w"); fputc('T',filepoint); fclose(filepoint); }
The above example will insert a single character ‘T’ in the 3.txt file.
3.txt
T
Reading from a file:- fgetc()
With the help of the fgetc() function, you can return a single character from a file.
Syntax:-
fgetc(FILE *stream);
Example of fgetc() function
#include <stdio.h> int main(){ FILE *ptr; char read; if (ptr = fopen("TechVidvan.txt", "r")){ while((read=fgetc(ptr))!=EOF) printf("Content of the file is: %c",read); } fclose(ptr); return 0; }
The above example will read from the file called TechVidvan.txt and display the contents of that file on the screen.
Output:-
fgets() and fputs() function in C:-
You can use fgets() and fputs() functions to write and read strings from a file.
Writing to a file:- fputs() function
WIth the help of fputs() function, you can write a line of characters into a file.
Syntax:-
fputs(char *string, FILE *filepointer);
Example of fputs() function
#include<stdio.h> #include<conio.h> void main(){ FILE *file; file=fopen("puts.txt","w"); fputs("TechVidvan Tutorial: Writing to a file in C!",file); fclose(file); getch(); }
After compiling and running the above program, it will write the line “TechVidvan Tutorial: Writing to a file in C” in a file called puts.txt.
puts.txt
TechVidvan Tutorial: Writing to a file in C!
Reading from a file:- fgets() function
With the help of fgets() function, you can read a line of characters from a file.
Syntax:-
fgets(char *string, length, FILE *ptr);
Example of fgets() function
#include<stdio.h> #include<conio.h> void main(){ FILE *file; char strings[300]; file=fopen("puts.txt","r"); printf("Content of the file is: %s",fgets(strings,200,file)); fclose(file); getch(); }
After compiling and running the above program, it will display the data which is stored inside the puts.txt file. And it will display the data on the screen.
Output:-
Summary
In this tutorial, we have discussed various file handling operations in C. We learnt that there are 2 types of data files in C. We also discussed several file handling functions in detail. With the help of file handling functions, you can create, edit, open, delete a file. You can also perform some file manipulating methods as well. Functions such as fprintf(), fscanf(), fgetc(), fputc(), fgets(), fputs() will help you in writing and reading to a file.