C Programming language

C - File Operation : Opening a file
Previous Home Next

Step for file operation in C programming:

  1. Open a file
  2. Read the file or write data in the file
  3. Close the file
Opening a file

A file must be open before any I/O operation can be performed on that file. The structure named File is defined in the file <stdio.h> that contains all information about the file like name, status, buffer size, current position, end of the file status.

A file pointer is a pointer to a structure of type FILE. whenever a  file opened, a structure of type FILE is associated with it, and the file pointer that points to the Structure identifies this file.

Every file you open has its own file pointer variable. When you wish to write to a file you specify the file by using its file pointer variable.

You declare these file pointer variables as follows:

FILE  *fopen(), *fp1, *fp2, *fp3;

The variables fp1, fp2, fp3 are file pointers. You may use any name you wish.

Declaration of fopen() function.

FILE * fopen( const char * filename ,const char *mode);

fopen( ) function takes two strings as arguments.

  • Name of the file to be opened
  • The Mode that decide which operations( read ,write , append) are to be performed on the file.

FILE *fp1, *fp2;

fp1=fopen( "ashish.txt", "w");

fp2=fopen( "anurag.txt", "r");

After opening the file with fopen( ) function, the name of the file is not used in the program for any operation on it.

Previous Home Next