File Handling

File Handling is the storing of data and in a file using a program.In C language the programs store results, and other data of the program to file using file handling in C. One such way to store the fetched information in a file. We may store into the local file system which is volatile and can be accessed every time.

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.

  • Creating of the new file
  • Opening an existing file
  • Reading from the file
  • Writing to the file
  • Deleting the file

Functions for the file handling

There are many functions in the C library to open, read, write , search and close the file.A list of file function are given below :

No.FunctionDescription
1 fopen()open new or existing file
2fprint()write data into the file
3fscanf() read data from the file
4fputc()write a character into the file
5fgetc() read a character from the file
6fclose() closes the file
7fseek()set the file pointer to given position
8fputw()writes an integer to file
9fgetw()read an integer from the file
10ftell()returns current position
11rewind()sets the file pointer to the beginning of the file

Opening file : fopen()

We open a file before it can be read, write or update.It loads the file from the disk and place into the buffer and the buffer provide efficiency for the read operations. The fopen() is used to open a file.

The syntax of the fopen() is given below :

FILE *fopen( const char * filename, const char * mode );

We can use one of the following modes in the fopen() function.

No.ModeDescription
1 ropen text file in read mode
2wopen text file in write mode
3aopen text file in append mode
4r+open text file in read and write mode
5w+open text file in read and write mode
6a+open text file in read and write mode
7rbopen a binary file in read mode
8wbopen a binary file in write mode
9abopen binary file in append mode
10rb+open binary file in read and write mode
11wb+open binary file in read and write mode
12ab+open binary file in read and write mode

Let’s see the example which opens a file in write mode

#include<stdio.h>  
void main( )  
{  
FILE *fp ;  
char ch ;  
fp = fopen("file_handle.c","r") ;  
while ( 1 )  
{  
ch = fgetc ( fp ) ;  
if ( ch == EOF )  
break ;  
printf("%c",ch) ;  
}  
fclose (fp ) ;  
}

Output

The content of the file will be printed.

Closing file : fclose()

The fclose() is used to close a file.The file must be closed after performing all the operations.

The Syntax of the fclose() is given below :

int fclose( FILE *fp );

Submit your review
1
2
3
4
5
Submit
     
Cancel

Create your own review

The Technical Funda
Average rating:  
 0 reviews