CodesJava

Easy learning with example program codes

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:

*modeFILEMODEDESCRIPTION
rText FileRead only modePointer starts from the beginning of the file.
wText FileWrite only modeOverwrites the existing file or creates a new file if it doesn’t exist. Pointer starts from the beginning of the file.
aText FileWrite only modeContinues 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 FileRead Write modePointer starts from the beginning of the file.
w+Text FileRead Write modeOverwrites the existing file or creates a new file if it doesn’t exist. Pointer starts from the beginning of the file.
a+Text FileRead Write modeContinues writing in the existing file or creates a new file if it doesn’t exist. Pointer starts from the end of the file.
rbBinary FileRead only modePointer starts from the beginning of the file.
wbBinary FileWrite only modeOverwrites the existing file or creates a new file if it doesn’t exist. Pointer starts from the beginning of the file.
abBinary FileWrite only modeContinues 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 FileRead Write modePointer starts from the beginning of the file.
wb+Binary FileRead Write modeOverwrites the existing file or creates a new file if it doesn’t exist. Pointer starts from the beginning of the file.
ab+Binary FileRead Write modeContinues 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.
Please follow and like us:
error
Posted in C   








Copyright © 2019 CodesJava DMCA.com Protection Status