In this section of C programming tutorial, we will have a look at file handling. The file represents the sequence of bytes on the disk where the group of related data is stored. The file is created for permanent storage of data.
What is File Handling in C
In the C programming language, file handling is used to permanently store data in files. It is used to open, store, read, search or close files.
The following operations can be performed on the file:
- Create a new file
- Opening an existing file
- Reading from file
- Write to file
- Delete file
There are different modes available for opening a file:
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 |
Example
#include <stdio.h> #include <conio.h> void main() { FILE *fptr; int rollno; char name[50]; fptr = fopen("student.txt", "w+");/* open for writing */ //student .txt is a file in which we store the data if (fptr == NULL) { printf("File does not exists \n"); return; } printf("Enter the Rollno\n"); scanf("%d", &rollno); fprintf(fptr, "Rollno= %d\n", rollno); printf("Enter the name \n"); scanf("%s", name); fprintf(fptr, "Name= %s\n", name); fclose(fptr); }
Output
Enter Rollno 20 Enter the name rishi
Then if we open the student.txt file then it contains-
Rollno = 20
Name = rishi
Functions for file handling
There are many functions in the C library to open, read, write, search and close the file. A list of file functions are given below:
- fopen() opens new or existing file
- fprintf() write data into file
- fscanf() reads data from file
- fputc() writes a character into file
- fgetc() reads a character from file
- fclose() closes the file
- fseek() sets the file pointer to given position
- fputw() writes an integer to file
- fgetw() reads an integer from file
- ftell() returns current position
- rewind() sets the file pointer to the beginning of the file