The FILE Pointer

The FILE pointer is the common thread that unites the C I/O system. A file pointer is pointer to a structure of type FILE. It points the information that defines various things about the file, including its name, status, and the current position of the file.

In order to read or writes files, your program needs to use file pointers.  

FILE *fp;

Opening a file

Before we can write a file to disk, or read it, we must open it. Opening a file establishes an understanding between our program and the operating system about which file we are going to access and how we are going to do it. We provide the operating system with the name of a file and other information like whether we plan to read or write to it.

Opening a file start with the declaration of variable of type pointer to a file in the statement as:

          FILE *fptr; //here fptr is the file pointer to the type FILE

Then we open the file with the syntax:

fptr=fopen(“file name”,”mode/stream”);

For example:


This statement opens a file named as name.text in write only mode.

Thus, fopen () function take two arguments. The first argument is the name of file to be opened and the second argument is the mode in which file has to be opened.

There are different modes for opening a file .The table below shows the legal values for mode.

Mode          Meaning

 r                 opens a text file for reading . To open a file in this mode the file must exist.

 w               opens a text file for writing. If the file exists, its contents will be written over, if does not exist a new file will be created.

 a                append to a text file. Data will be added at the bottom of the file if the file already exists otherwise a new one will be created.

r+                Opens a text file for both reading and writing.
The file must exist.

w+              Opens a text file for both reading and writing .If the file already exits its content are overwritten and if does not exist then a new file will be created.

a+               Opens a text file for both reading and appending .If file does not exits it will be created.


                   Closing a file :

The fclose() function closes a stream that was opened by a call to fopen().The fclose() function has this prototype:

int fclose(FILE *fp);

Here, fp is the file pointer returned by the call to fopen(). A return value 0 signifies a successful operation. The function returns EOF if an error occurs. We can use the standard function ferror() to determine and report any problems. Generally fclose() will fail only when a disk has been permanently removed from the drive or there is no more space in the disk. The opened file is closed with the following statement:



File handling (Prev Lesson)
(Next Lesson) Character input/Output functions in file
Back to C-Programming

No Comments

Post a Reply

Bhim Gautam
Role : Lecturer
Read More
error: Content is protected !!