In this tutorial you will learn about the C File Handling and its application with practical example.
A file is a collection of streamed bytes stored on a secondary storage device. This streamed byte can be interpreted as characters, words, lines, paragraphs, and pages of a textual document; fields and records belonging to a database; or pixels from a graphical image. Through the file handling function, we can create, modify, move or delete files on the system. In every programming language, it is important to implement a file handling function. In C Programming Language a Special set of functions have been designed for c file handling operations.
Some of the basic file handling operations are-
- Open & Close files
- Read from & Write to files
- Delete files.
Functions for all of the above operations are available in the stdio.h header file.
C File HandlingOperations:
Opening & Closing Files (fopen() and fclose())
In C Programming Language before we perform any operations on a file, we must open it first, this can be done using the fopen function, which returns the pointer to the required. If the file cannot be opened for any reason then the value NULL will be returned.
Syntax:
1 |
FILE * fopen(char * filename, char * mode) |
The fopen() function is used to open a file and associate an I/O stream with it. C file handling function takes two arguments. The first argument is a pointer to a string containing the name of the file to be opened while the second argument is the mode in which the file is to be opened. The mode can be :
r | Open for reading |
r+ | Open for reading and writing |
w | Open for writing and create the file if it does not exist. If the file exists then make it blank. |
w+ | Open for reading and writing and create the file if it does not exist. If the file exists then make it blank. |
a | Open for appending(writing at the end of the file) and create the file if it does not exist. |
a+ | Open for reading and appending and create the file if it does not exist. |
Below is the code snippet for opening and closing a file –
1 2 3 4 5 6 7 8 9 10 11 |
FILE * hFile; hFile = fopen(filename, "r"); if (hFile == NULL) { // Error, file not found } else { // Process & close file fclose(hFile); } |
The fclose() function is used for closing opened files.
Syntax:
1 |
fclose(FILE *fptr) |
The only argument it accepts is the file pointer. If a program terminates, it automatically closes all opened files. Upon successful completion, this function returns 0 else end of the file (eof) is returned. In case of failure, if the stream is accessed further then the behavior remains undefined. But it is a good programming habit to close any file once it is no longer needed. C file handling helps in better utilization of system resources and is very useful when you are working on numerous files simultaneously. Some operating systems place a limit on the number of files that can be open at any given point in time.
Read from & Write to files
Once a file is open, we can read from it or write into it in the following ways –
Character Input and Output – fgetc() and fputc()
fgetc() – Function fgetc() reads a single character from the file which has previously been opened using a function like fopen().
Syntax:
1 |
fgetc(fp); |
fp – file pointer
fputc() – Functionf putc() does the opposite, it writes a character to the file identified by its second argument.
Syntax:
1 |
fputc(c, fp); |
The second argument in the putc() function must be a file opened in either write or append mode.
Example:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 |
#include <stdio.h> main () { char in_file[30], out_file[30]; FILE *fpin, *fpout; int c; printf("This program copies the source file to the destination file \n\n"); printf("Enter name of the source file :"); scanf("%30s", in_file); printf("Enter name of the destination file :"); scanf("%30s", out_file); if((fpin=fopen(in_file, "r")) == NULL) printf("Error could not open source file for reading\n"); else if ((fpout=fopen(out_file, "w")) == NULL) printf("Error could not open destination file for reading\n"); else { while((c =getc(fpin)) != EOF) putc(c, fpout); printf("Destination file has been copied\n"); } } |
Formatted Input Output – fprintf() and fscanf()
fprintf – The fprintf() function is used for formatted write to file. It returns a number of characters printed or a negative number on error.
Syntax:
1 |
int fprintf(FILE *ptr,char * fmt,…) |
fscanf– The fscanf() function is used for formatted read from files. It returns a number of values read successfully.
Syntax:
1 |
int fscanf(FILE *ptr,char * fmt,…) |
Example:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 |
#include <stdio.h> main () { FILE *fp; float total; fp = fopen("data.txt", "w+") if (fp == NULL) { printf("data.txt does not exist, please check!\n"); exit (1); } fprintf(fp, 100); fscanf(fp, "%f", &total); fclose(fp); printf("Value of total is %f\n", total); } |
Binary File Input Output – fread() and fwrite()
fread() – It reads from binary file.
Syntax:
1 |
int fread(void * buffer, int size, int num, FILE * ptr) |
buffer – stores the value read, size – the size of the buffer, num – number of blocks to be read, ptr – file pointer
If it encounters an error or end-of-file, it returns a zero, you have to use feof() or ferror() to distinguish between these two.
fwrite() – It write to a binary file.
Syntax:
1 |
int fwrite(void * buffer, int size, int num, FILE * ptr) |
buffer – stores the value read, size – the size of the buffer, num – number of blocks to be read, ptr – file pointer
It returns the number of items written to ptr.
fseek() – It moves the file pointer by the given offset.
Syntax:
1 |
int fseek(FILE*ptr,long offset,int whence) |
ptr – file pointer, offset – offset in bytes from third parameter
whence(SEEK_SET – from the beginning of the file, SEEK_CUR – from the current position, SEEK_END – from the end of file)
It returns a zero on success and a non-zero on failure.
ftell() – It tells the position of the file pointer.
syntax:
1 |
int ftell(FILE *ptr) |
ptr – FILE pointer
It returns the position of the pointer on success or -1 on error.
Example:
1 2 3 |
FILE *ptr = fopen(b[1],"r"); fseek(ptr,0L,SEEK_END); int size_of_file = ftell(ptr); |
rewind() – It sets the file pointer to the beginning of the file.
Syntax:
1 |
void rewind(FILE *ptr) |
ptr – FILE pointer
Example:
1 2 |
rewind(infile); int n = fscanf(infile,"%d",&n); |
EOF (The End of File Marker)
EOF is a character that indicates the end of a file. It is returned by reading commands when they try to read beyond the end of a file.