C File Handling

C File Handling:

File handling simply means to open a file and to process it according to the required tasks. C facilitates several functions to create, read, write, append, delete and close files.

❏     Open File:

To open a file in C, fopen() function is used.

❏     Close File:

To close a file in C, fclose() function is used. 

❏     Read File:

To read a file in C, fscanf() function is used.

❏     Write File:

To write a file in C, fprintf() function is used.

C Open File:

To open a file in C, fopen() function is used. In general, fopen() function accepts two parameters:

Filename:  This parameter specifies the name of the file to be opened.

Mode: This parameter specifies the mode in which the file should be opened.

Syntax:

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

MODES of fopen function:

*mode FILE MODE DESCRIPTION
r Text File Read only mode Pointer starts from the beginning of the file.
w Text File Write only mode Overwrites the existing file or creates a new file if it doesn’t exist. Pointer starts from the beginning of the file.
a Text File Write only mode Continues writing in the existing file or creates a new file if it doesn’t exist. Pointer starts from the end of the file.
r+ Text File Read Write mode Pointer starts from the beginning of the file.
w+ Text File Read Write mode Overwrites the existing file or creates a new file if it doesn’t exist. Pointer starts from the beginning of the file.
a+ Text File Read Write mode Continues writing in the existing file or creates a new file if it doesn’t exist. Pointer starts from the end of the file.
rb Binary File Read only mode Pointer starts from the beginning of the file.
wb Binary File Write only mode Overwrites the existing file or creates a new file if it doesn’t exist. Pointer starts from the beginning of the file.
ab Binary File Write only mode Continues writing in the existing file or creates a new file if it doesn’t exist. Pointer starts from the end of the file.
rb+ Binary File Read Write mode Pointer starts from the beginning of the file.
wb+ Binary File Read Write mode Overwrites the existing file or creates a new file if it doesn’t exist. Pointer starts from the beginning of the file.
ab+ Binary File Read Write mode Continues writing in the existing file or creates a new file if it doesn’t exist. Pointer starts from the end of the file.

Example:

#include <stdio.h>  
void main()
{  
FILE *f;  
f = fopen("file.txt", "w");
fprintf(f, "Reading data from a file is a common feature of file handling.\n");
fclose(f);
 
char arr[50];
f = fopen("file.txt", "r");  
while(fscanf(f, "%s", arr)!=EOF){  
printf("%s ", arr);  
}  
fclose(f);  
}

Output

Reading data from a file is a common feature of file handling.