C opening & defining FILE

Before opening the file we must understand the basic concept of file in C Programming , Types of File. If we want to display some message on the console from the file then we must open it in read mode.

Opening and Defining FILE in C Programming

Before storing data onto the secondary storage , firstly we must specify following things –

  1. File name
  2. Data Structure
  3. Perpose / Mode
  4. Very first task in File handling is to open file

File name : Specifies Name of the File

File Extension in C Programming

  1. File name consists of two fields
  2. First field is name field and second field is of extension field
  3. Extension field is optional
  4. Both File name and extension are separated by period or dot.

Data Structure :

  1. Data structure of file is defined as FILE in the library of standered I/O functions
  2. In short we have to declare the pointer variable of type FILE

Mode of FILE opening :

In C Programming we can open file in different modes such as reading mode,writing mode and appending mode depending on purpose of handling file.

Following are the different Opening modes of File :

Opening Mode Purpose Previous Data
Reading File will be opened just for reading purpose Retained
Writing File will be opened just for writing purpose Flushed
Appending File will be opened for appending some thing in file Retained

Different Steps to Open File :

Step 1 : Declaring FILE pointer

Firstly we need pointer variable which can point to file. below is the syntax for declaring the file pointer.

FILE *fp;

Step 2 : Opening file hello.txt

fp = fopen ("filename","mode");

Live Example : Opening the File and Defining the File


int main()
FILE *fp;
char ch;

fp = fopen("INPUT.txt","r") // Open file in Read mode

fclose(fp); // Close File after Reading


If we want to open file in different mode then following syntax will be used –

Reading Mode
fp = fopen("hello.txt","r");
Writing Mode
fp = fopen("hello.txt","w");
Append Mode
fp = fopen("hello.txt","a");

Opening the File : Yet Another Live Example


void main()
 FILE *fp;
 char ch;
 fp = fopen("INPUT.txt","r"); // Open file in Read mode

   ch = fgetc(fp); // Read a Character
      if(ch == EOF ) // Check for End of File
         break ;

 fclose(fp); // Close File after Reading