C Programming Tutorial
Computer Tutorial

Opening a File

Opening a File

Before we can read (or write) information from (to) a file on a disk we must open the file. To open the file we have called the function fopen( ). It would open a file “PR1.C” in ‘read’ mode, which tells the C compiler that we would be reading the contents of the file. Note that “r” is a string and not a character; hence the double quotes and not single quotes. In fact fopen( ) performs three important tasks when you open the file in “r” mode:

The fopen( ) function has this prototype :
FILE *fopen(const char *filename, const char *mode);

Firstly it searches on the disk the file to be opened. Then it loads the file from the disk into a place in memory called buffer. It sets up a character pointer that points to the first character of the buffer.
To be able to successfully read from a file information like mode of opening, size of file, place in the file from where the next read operation would be performed, etc. has to be maintained. Since all this information is inter-related, all of it is gathered together by fopen( ) in a structure called FILE. fopen( ) returns the address of this structure, which we have collected in the structure pointer called fp. We have declared fp as :
FILE *fp;

fp = fopen("test", "w");

The FILE structure has been defined in the header file “stdio.h” (standing for standard input/output header file). Therefore, it is necessary to #include this file.