Opening a file in C

We can perform read and write operations on a file in C. But, before that we must open a file. To open a file in C, we have to call the function fopen() as shown below:

FILE *fp;
fp = fopen("file1.C","r");

The above statement would open file named “file1.C” in “read” mode. It tells the computer that the file being opened would be used for reading purpose only.
fopen() performs three important tasks when you open the file in “r” mode:

  1. Firstly, it searches the file to be opened on the disk
  2. Then it loads the file from the disk into the place in memory called buffer
  3. It sets up a character pointer that points to the first character of the buffer

All the file information 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” (standard for standard input/output header file). Therefore, it is mandatory to use #include.

You may also like...

2 Responses

  1. mohammed says:

    sir, i don,t understand why we use pointer file *fp; plz help

  1. July 7, 2020

    […] Opening a file […]

Leave a Reply

Your email address will not be published. Required fields are marked *

FREE C Cheatsheet - Speed Up Your C Programming.

FREE C Cheatsheet - Speed Up Your C Programming.

Download a 7-page free cheat sheet for easy and quick access to C Concepts, Snippets, and Syntax.

Thank you! Check you inbox and access your cheat-sheet