File Handling in C
In programming, we may require some specific input data to be generated several numbers of times. Sometimes, it is not enough to only display the data on the console. The data to be displayed may be very large, and only a limited amount of data can be displayed on the console, and since the memory is volatile, it is impossible to recover the programmatically generated data again and again. However, if we need to do so, we may store it onto the local file system which is volatile and can be accessed every time. Here, comes the need of file handling in C.
File handling in C enables us to create, update, read, and delete the files stored on the local file system through our C program. The following operations can be performed on a file.
- Creation of the new file
- Opening an existing file
- Reading from the file
- Writing to the file
- Deleting the file
Consider the following example which opens a file in write mode.
Output
The content of the file will be printed.
#include; void main( ) { FILE *fp; // file pointer char ch; fp = fopen("file_handle.c","r"); while ( 1 ) { ch = fgetc ( fp ); //Each character of the file is read and stored in the character file. if ( ch == EOF ) break; printf("%c",ch); } fclose (fp ); }
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 |
Writing File : fprintf() function
The fprintf() function is used to write set of characters into file. It sends formatted output to a stream.
Syntax:
Example:
Writing File : fputc() function
The fputc() function is used to write a single character into file. It outputs a character to a stream.
Syntax:
Example:
Reading File : fgetc() function
The fgetc() function returns a single character from the file. It gets a character from the stream. It returns EOF at the end of file.
Syntax:
Example:
myfile.txt
this is simple text message
this is simple text message
Closing File: fclose()
The fclose() function is used to close a file. The file must be closed after performing all the operations on it. The syntax of fclose() function is given below: