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
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:No.FunctionDescription
1 fopen()-opens new or existing file
2 fprintf()-write data into the file
3 fscanf()-reads data from the file
4 fputc()-writes a character into the file
5 fgetc()-reads a character from file
6 fclose()-closes the file
7 fseek()-sets the file pointer to given position
8 fputw() writes an integer to file
9 fgetw()reads an integer from file
10 ftell()-returns current position
11 rewind()-sets the file pointer to the beginning of the file
Opening File: fopen()
We must open a file before it can be read, write, or update. The fopen() function is used to open a file. The syntax of the fopen() is given below.
- FILE *fopen( const char * filename, const char * mode );
The fopen() function accepts two parameters:
- The file name (string). If the file is stored at some specific location, then we must mention the path at which the file is stored. For example, a file name can be like “c://some_folder/some_file.ext”.
- The mode in which the file is to be opened. It is a string.
We can use one of the following modes in the fopen() function.ModeDescriptionropens a text file in read modewopens a text file in write modeaopens a text file in append moder+opens a text file in read and write modew+opens a text file in read and write modea+opens a text file in read and write moderbopens a binary file in read modewbopens a binary file in write modeabopens a binary file in append moderb+opens a binary file in read and write modewb+opens a binary file in read and write modeab+opens a binary file in read and write mode
The fopen function works in the following way.
- Firstly, It searches the file to be opened.
- Then, it loads the file from the disk and place it into the buffer. The buffer is used to provide efficiency for the read operations.
- It sets up a character pointer which points to the first character of the file.
Consider the following 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. #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 ); }
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:
- int fclose( FILE *fp );
feof()
Description
The C library function int feof(FILE *stream) tests the end-of-file indicator for the given stream.
Declaration
Following is the declaration for feof() function.
int feof(FILE *stream)
Parameters
- stream − This is the pointer to a FILE object that identifies the stream.
Return Value
This function returns a non-zero value when End-of-File indicator associated with the stream is set, else zero is returned.
Example
The following example shows the usage of feof() function.
#include <stdio.h> int main () { FILE *fp; int c; fp = fopen("file.txt","r"); if(fp == NULL) { perror("Error in opening file"); return(-1); } while(1) { c = fgetc(fp); if( feof(fp) ) { break ; } printf("%c", c); } fclose(fp); return(0); }
rewind( )
Description
The C library function void rewind(FILE *stream) sets the file position to the beginning of the file of the given stream.
Declaration
Following is the declaration for rewind() function.
void rewind(FILE *stream)
Parameters
- stream − This is the pointer to a FILE object that identifies the stream.
Return Value
This function does not return any value.
Example
The following example shows the usage of rewind() function.
#include <stdio.h> int main () { char str[] = "This is tutorialspoint.com"; FILE *fp; int ch; /* First let's write some content in the file */ fp = fopen( "file.txt" , "w" ); fwrite(str , 1 , sizeof(str) , fp ); fclose(fp); fp = fopen( "file.txt" , "r" ); while(1) { ch = fgetc(fp); if( feof(fp) ) { break ; } printf("%c", ch); } rewind(fp); printf("\n"); while(1) { ch = fgetc(fp); if( feof(fp) ) { break ; } printf("%c", ch); } fclose(fp); return(0); }
fputc() and fgetc()
Writing File : fputc() function
The fputc() function is used to write a single character into file. It outputs a character to a stream.
Syntax:
- int fputc(int c, FILE *stream)
Example:
- #include <stdio.h>
- main(){
- FILE *fp;
- fp = fopen(“file1.txt”, “w”);//opening file
- fputc(‘a’,fp);//writing single character into file
- fclose(fp);//closing file
- }
file1.txta
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:
- int fgetc(FILE *stream)
Example:
- #include<stdio.h>
- #include<conio.h>
- void main(){
- FILE *fp;
- char c;
- clrscr();
- fp=fopen(“myfile.txt”,”r”);
- while((c=fgetc(fp))!=EOF){
- printf(“%c”,c);
- }
- fclose(fp);
- getch();
- }
myfile.txtthis is simple text message
fseek() function
The fseek() function is used to set the file pointer to the specified offset. It is used to write data into file at desired location.
Syntax:
- int fseek(FILE *stream, long int offset, int whence)
There are 3 constants used in the fseek() function for whence: SEEK_SET, SEEK_CUR and SEEK_END.
Example:
- #include <stdio.h>
- void main(){
- FILE *fp;
- fp = fopen(“myfile.txt”,”w+”);
- fputs(“This is javatpoint”, fp);
- fseek( fp, 7, SEEK_SET );
- fputs(“sonoo jaiswal”, fp);
- fclose(fp);
- }
myfile.txtThis is sonoo jaiswal
fscanf( )
fscanf function reads formatted input from a file. This function is implemented in file related programs for reading formatted data from any file that is specified in the program
syntax
int fscanf(FILE *stream, const char *format, ...)
Its return the number of variables that are assigned values, or EOF if no assignments could be made.