File handling in C
A file is a collection of bytes stored on a secondary storage device, which is generally a disk of some kind.
A file can be a text file or a binary file depending upon its contents.
Through file handling, one can perform operations like create, modify, delete etc on system files.
File I/O can be performed on a character by character basis, a line by line basis, a record by record basis or a chunk by chunk basis.
Special functions have been designed for handling file operations. The header file stdio.h is required for using these functions.
C provides a number of functions that helps to perform basic file operations. Following are the functions,
Function | Description |
---|---|
fopen( ) | create a new file or open a existing file |
fclose( ) | closes a file |
getc( ) | reads a character from a file |
putc( ) | writes a character to a file |
fscanf( ) | reads a set of data from a file |
fprintf( ) | writes a set of data to a file |
getw( ) | reads a integer from a file |
putw( ) | writes a integer to a file |
fseek( ) | set the position to desire point |
ftell( ) | gives current position in the file |
rewind( ) | set the position to the begining point |
File Operations :
In C, you can perform the following operations :- Create a new file
- Open an existing file
- Close a file
- Reading from an writing to a file.
Opening/Create a File :
Before we perform any operations on a file, we need to identify the file to the system and open/create it. We do this by using a file pointer. The type FILE structure defined in stdio.h allows us to define a file pointer. Then we use the function fopen() for opening/create a file. Once this is done one can read or write to the file using the fread() or fwrite() functions, respectively. The fclose() function is used to explicitly close any opened file.
fopen( )
Syntax :
FILE *fopen( const char * filename, const char * mode );
Before we read (or write) information from (to) a file on a disk we must open the file. To open the file we call the function fopen( ).
fopen( ) returns the address of the file, which we collect in the File type pointer. We declare File pointer as
File *fp
Syntax to open/create filers
fp = fopen("file name","opening mode");
This function accepts two arguments as strings. The first argument denotes the name of the file to be opened and the second signifies the mode in which the file is to be opened.
The second argument can be any of the following:
Mode | Description | What if file doesn't exist |
---|---|---|
r | Open text file for reading.The stream is positioned at the beginning of the file. | If file doesn't exist, then fopen() returns NULL. |
w | Open text file for writing. | If file exist, it truncate the contents.If doesn't exist, then fopen() creates the file. |
a | Open text file for appending (writing at end of file). | The file is created if it does not exist. The stream is positioned at the end of the file. |
r+ | Open text file for reading and writing. | If file doesn't exist, then fopen() returns NULL. |
w+ | Open text file for reading and writing. | If file exist, it truncate the contents.If doesn't exist, then fopen() creates the file. |
a+ | Open for reading and appending (writing at end of file). | The file is created if it does not exist. The initial file position for reading is at the beginning of the file, but output is always appended to the end of the file. |
Now, if you want to work with binary files, then use the following modes instead of above mentioned
"rb", "wb", "ab", "rb+", "r+b", "wb+", "w+b", "ab+", "a+b"
Closing a File:
It is a good practice, the file (both text and binary) should be closed after reading/writing operation completed.
The fclose() function is used for closing opened files. The only argument it accepts is the file pointer.
Syntax:
int fclose( FILE *fp );The fclose() function returns zero(0) on success, or EOF if there is an error in closing the file.
Reading/Writing to a text File :
There are too many functions are available to perform read/write operations on a text file, let us see one-by-one with example.
Write to a text file character by character using fputc()
function.
fputc(ch,fp)
#include<stdio.h> int main( ) { FILE *fp; char str[20] = "C Prowess"; int i=0; fp = fopen("test.txt","w"); //mode 'w' for write. if(fp != NULL){ //check file is open. while(str[i]!='\0'){ fputc(str[i], fp);//writing char-by-char. i++; } fclose(fp); //closing the file. printf("File Data Saved!!"); } else{ printf("Error in file opening.'"); } return 0; }Output :
File Data Saved!!
Reading from a text file character by character using fgetc()
function.
char c = fgetc(fp)
#include<stdio.h> int main( ) { FILE *fp; char ch; fp = fopen("test.txt","r"); //mode 'r' for reading. if(fp != NULL){ //check file is open. do{ ch = fgetc(fp);//reading char-by-char. printf("%c",ch); }while(ch!=EOF); fclose(fp); //closing the file. } else{ printf("Error in File opening"); } return 0; }Output :
C Prowess
Writing using fputs()
and fprintf()
.
#include<stdio.h> int main( ) { FILE *fp; fp = fopen("test.txt","w"); if(fp != NULL){ fprintf(fp,"This is writing through fprintf function ...\n"); fputs("This is writing through fputs function...\n",fp); printf("Data Saved."); fclose(fp); } else{ printf("Error in File opening."); } return 0; }Output :
Data Saved.
Reading using fgets()
and fscanf()
.
#include<stdio.h> int main( ) { #includeOutput :int main( ) { FILE *fp; char buff[255]; fp = fopen("test.txt", "r"); fscanf(fp, "%s", buff); printf("1 : %s\n", buff ); fgets(buff, 255, (FILE*)fp); printf("2 : %s\n", buff ); fgets(buff, 255, (FILE*)fp); printf("3 : %s\n", buff ); fclose(fp); return 0; }
1 : This 2 : is writing through fprintf function ... 3 : This is writing through fputs function...
Copy content from a file to another file.
#include<stdio.h> int main( ) { FILE *fp =NULL, *fp1=NULL; char ch; fp = fopen("from.txt","r"); fp1 = fopen("to.txt","w"); if(fp!=NULL && fp1!=NULL){ while((ch = fgetc(fp))!=EOF){ fputc(ch,fp1); } fclose(fp); fclose(fp1); printf("Copy Done!!!"); } else printf("ERROR!!"); return 0; }
ftell()
Function ftell() returns the current position of the file pointer in a stream. The return value is 0 or a positive integer indicating the byte offset from the beginning of an open file. A return value of -1 indicates an error.
Syntax :
long int ftell(FILE *fp);
Example :
#include<stdio.h> int main( ) { FILE *fp =NULL; char ch; fp = fopen("test.txt","r"); if(fp!=NULL){ printf("CURRENT POSITION %d\n",ftell(fp)); fgetc(fp); printf("AFTER READING POSITION %d",ftell(fp)); } else printf("ERROR!!"); return 0; }Output :
CURRENT POSITION 0 AFTER READING POSITION 1
fseek()
This function positions the next I/O operation on an open stream to a new position, relative to the current position.
Syntax :
int fseek(FILE *fp, long int offset, int origin);
Here, fp is the file pointer of the stream on which I/O operations are carried on.
offset is the number of bytes to skip over. The offset can be either positive or negative, denting forward or backward movement in the file.
origin is the position in the stream to which the offset is applied, this can be one of the following constants :
origin | meaning |
---|---|
SEEK_SET | Starts the offset from the beginning of the file. |
SEEK_CUR | Starts the offset from the end of the file. |
SEEK_END | Starts the offset from the current location of the cursor in the file. |
Example :
#include<stdio.h> int main( ){ FILE *fp =NULL; char ch; fp = fopen("test.txt","r"); if(fp!=NULL){ fseek(fp,3,SEEK_SET); while((ch=fgetc(fp))!=EOF){ printf("%c",ch); } } else printf("ERROR!!"); return 0; }
This program will start the reading from 3rd byte from the beginning of file.
rewind()
It moves the control to beginning of the file.
Syntax :
void rewind(FILE *fp)
Next topic is pre-processor in C
Training For College Campus
We offers college campus training for all streams like CS, IT, ECE, Mechanical, Civil etc. on different technologies
like
C, C++, Data Structure, Core Java, Advance Java, Struts Framework, Hibernate, Python, Android, Big-Data, Ebedded & Robotics etc.
Please mail your requirement at info@prowessapps.in
Projects For Students
Students can contact us for their projects on different technologies Core Java, Advance Java, Android etc.
Students can mail requirement at info@prowessapps.in