Opening a File in C

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:

  • 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.

Every time we read something from a disk, it takes some time for the disk drive to position the read/write head correctly. On a floppy disk system, the drive motor has to actually start rotating the disk from a standstill position every time the disk is accessed. If this were to be done for every character we read from the disk, it would take a long time to complete the reading operation. This is where a buffer comes in. It would be more sensible to read the contents of the file into the buffer while opening the file and then read the file character by character from the buffer rather than from the disk.

Opening a File in C
Opening a File in C

Same argument also applies to writing information in a file. Instead of writing characters in the file on the disk one character at a time it would be more efficient to write characters in a buffer and then finally transfer the contents from the buffer to the disk.

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 ;

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.

Leave a Comment