File Handling in C Language
A file represents a sequence of bytes on the disk where a group of related data is stored. File is created for permanent storage of data. It is a ready made structure.Opening Files
You can use the fopen( ) function to create a new file or to open an existing file.
General Syntax :
*fp = FILE *fopen(const char *filename, const char *mode);
Here filename is the name of the file to be opened and mode specifies the purpose of opening the file. Mode can be of following types,
*fp is the FILE pointer (
FILE *fp
), which will hold the reference to the opened(or created) file.Mode | Description |
---|---|
r | Opens an existing text file for reading purpose. |
w | Opens a text file for writing, if it does not exist then a new file is created. Here your program will start writing content from the beginning of the file. |
a | Opens a text file for writing in appending mode, if it does not exist then a new file is created. Here your program will start appending content in the existing file content. |
r+ | Opens a text file for reading and writing both. |
w+ | Opens a text file for reading and writing both. It first truncate the file to zero length if it exists otherwise create the file if it does not exist. |
a+ | Opens a text file for reading and writing both. It creates the file if it does not exist. The reading will start from the beginning but writing can only be appended. |
fclose()
function is used to close an already opened file.Closing a File
General Syntax :
int fclose( FILE *fp );Here fclose() function closes the file and returns zero on success, or EOF if there is an error in closing the file. This EOF is a constant defined in the header file stdio.h.
Writing a File
Following is the simplest function to write individual characters to a stream:
int fputc( int c, FILE *fp );
The function fputc() writes the character value of the argument c to the output stream referenced by fp. It returns the written character written on success otherwise EOF if there is an error. You can use the following functions to write a null-terminated string to a stream:
int fputs( const char *s, FILE *fp );
The function fputs() writes the string s to the output stream referenced by fp. It returns a non-negative value on success, otherwise EOF is returned in case of any error. You can use int fprintf(FILE *fp,const char *format, ...) function as well to write a string into a file.
Try the following example:
#include <stdio.h> main() { FILE *fp; fp = fopen("/tmp/test.txt", "w+"); fprintf(fp, "This is testing for fprintf...\n"); fputs("This is testing for fputs...\n", fp); fclose(fp); }
When the above code is compiled and executed, it creates a new file test.txt in /tmp directory and writes two lines using two different functions. Let us read this file in next section.
Reading a File
Following is the simplest function to read a single character from a file:
int fgetc( FILE * fp );
The fgetc() function reads a character from the input file referenced by fp. The return value is the character read, or in case of any error it returns EOF.
char *fgets( char *buf, int n, FILE *fp );
The functions fgets() reads up to n - 1 characters from the input stream referenced by fp. It copies the read string into the buffer buf, appending a null character to terminate the string.
If this function encounters a newline character '\n' or the end of the file EOF before they have read the maximum number of characters, then it returns only the characters read up to that point including new line character. You can also use int fscanf(FILE *fp, const char *format, ...) function to read strings from a file but it stops reading after the first space character encounters..
#include <stdio.h> main() { FILE *fp; char buff[255]; fp = fopen("/tmp/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); }
When the above code is compiled and executed, it reads the file created in previous section and produces the following result:
1 : This 2: is testing for fprintf... 3: This is testing for fputs...
Let's see a little more detail about what happened here. First fscanf() method read just Thisbecause after that it encountered a space, second call is for fgets() which read the remaining line till it encountered end of line. Finally last call fgets() read second line completely.
Input/Output operation on File
#include<stdio.h> #include<conio.h> main() { FILE *fp; char ch; fp = fopen("one.txt", "w"); printf("Enter data"); while( (ch = getchar()) != EOF) { putc(ch,fp); } fclose(fp); fp = fopen("one.txt", "r"); while( (ch = getc()) != EOF) printf("%c",ch); fclose(fp); }
Reading and Writing from File using fprintf() & fscanf()
#include<stdio.h> #include<conio.h> struct emp { char name[10]; int age; }; void main() { struct emp e; FILE *p,*q; p = fopen("one.txt", "a"); q = fopen("one.txt", "r"); printf("Enter Name and Age"); scanf("%s %d", e.name, &e.age); fprintf(p,"%s %d", e.name, e.age); fclose(p); do { fscanf(q,"%s %d", e.name, e.age); printf("%s %d", e.name, e.age); } while( !feof(q) ); getch(); }In this program, we have create two FILE pointers and both are refering to the same file but in different modes.fprintf() function directly writes into the file, while fscanf() reads from the file, which can then be printed on console usinf standard printf() function.
Difference between Append and Write Mode
Write (w) mode and Append (a) mode, while opening a file are almost the same. Both are used to write in a file. In both the modes, new file is created if it doesn't exists already.
The only difference they have is, when you open a file in the write mode, the file is reset, resulting in deletion of any data already present in the file. While in append mode this will not happen. Append mode is used to append or add data to the existing data of file(if any). Hence, when you open a file in Append(a) mode, the cursor is positioned at the end of the present data in the file.
fseek(), ftell() and rewind() functions
- fseek() - It is used to move the reading control to different positions using fseek function.
- ftell() - It tells the byte location of current position of cursor in file pointer.
- rewind() - It moves the control to beginning of the file.