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:
- Firstly, it searches the file to be opened on the disk
- Then it loads the file from the disk into the place in memory called buffer
- 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
.
sir, i don,t understand why we use pointer file *fp; plz help