How to define and open a file in C programming

If the user wants to store data or read data from a file in the secondary memory, the user must specify certain things about the file to the operating system. They are:

  1. Filename
  2. Data Structure
  3. Purpose

Filename is the name of the file. It is a collection of characters that make up a valid filename for the operating system. It may contain two parts: a primary name and optional period with the etxtension. Some valid file names are:




Data Structure of a file is defined a FILE in the C library. Therefore, all files should be declared as type FILEbefore they are used. FILE is a predefined data type. When we open a file, we must specify the purpose. For example, we may want to write data or read data from a file. The syntax for declaring and opening a file is:

The first statement declares the variable fp as a pointer to the data type FILE. The second statement opens the file whose name is filename and assigns an identifier to the FILE type pointer fp. This pointer, which contains all the information about the file is subsequently used as a communication link between the system and the program. The mode specifies the purpose of opening the file. Mode can be one of the following:

  • r opening the file for reading data from it
  • w opening the file for writing data to it
  • a opening the file for appending data to it

Note that both filename and mode are specified as string. So, both of them must be enclosed within double quotes. Some compilers support the following additional modes:

  • r+ Open the existing file for both reading and writing
  • w+ Open the file for both reading and writing
  • a+ Open the file for both appending and reading

Note: When a file is opened in r mode, the compiler searches for the file and if the file does not exist, nothing happens or some compilers might generate an error. When a file is opened in w mode, the compiler searches for the file and if the file does not exist, it creates a new file with the specified name. If the file already exists, the file is opened with the all the previous data in the file erased.


Closing a File

A file must be closed as soon as all the operations on it have been finished. This ensures that all information associated with the file is flushed out from the buffers and all links to the file with the program are broken. It also prevents the accidental misuse of the file. Another case in which we might want to close the connection with the file is, when we want to reopen the same file in a different mode.


1 Comment

Leave a Response