Files - 1 File Handling

File Handling in C 



       Programming editors like turbo C/C++ allows us to store our programs but not the output produced by our programs. Hence to store the output of program into secondary memory in the form file we make use of File Handling feature in C. C has a data type called FILE. C language provides different functions to handle the file operation.To work with files one need to declare the a pointer to FILE. Its syntax is as followed,



FILE *fp;


fp is a pointer to FILE.

Next step is to make fp to point to some file it can be done using a function called fopen(). Syntax for fopen() is as follows,

fp = fopen( "filename", "mode");

fopen() contains two arguments namely filename and mode.        

"filename" represents the name of file on which we perform operation. Name of file may be any valid DOS file name. File names may be in uppercase or lowercase. Even the path for file name can be included provided \ must be written twice.

"mode" represent in which of the following mode the file has to opened. Operations to be performed on the file depends on this mode only. C language provides different modes in which a file can be opened and they are liste below.

r - open for reading only
w  - open for writing 
a  - open for appending 
r+ - open for reading and writing
w+ - open for reading and writing  

a+ - open for reading and writing 

File mode r : r means read only means file is opened for reading only for existing files, it fails if file does not exist. File pointer will be placed at the beginning of the file.


File mode w : w means write only, means file is opened for writing only for existing/non existing files. If file is existing it overwrites the file, if not it creates a new file and writes the contents.

File mode a : a stands for append, means the existing file which already has some contents this will add contents from end of the file without erasing/overwriting contents of file. 

File mode r+, w+, a+ : These + operator indicates that along with their basic operation read and write operations can also be done.

fclose() function :

    This function is used to close the file after completing I/O(input/output) operation. After this no operation can be done on the file. If we want to perform do any operation like read/write/append then the file has to be reopened using fopen().

Syntax : 

fclose(filepointer);

Example :

fclose(fp);

Comments