C fopen() function : <stdio.h>

Opening file in C : fopen function (stdio.h Function)

Syntax of Declaring FILE pointer

FILE *fp;

Syntax of Opening file hello.txt

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

How to open file in C ?

  1. fopen opens a stream
  2. fopen open a file and associate a stream with it.
  3. functions return a pointer that identifies the stream in subsequent operations.
  4. FILE will be opened for following purposes –
    • Reading data file
    • Writing on data file
    • Appending Content to the file

Explanation :

  1. In simple words fopen function will open file specified in the specified mode.
  2. We have different file opening modes in C Programming. [ Refer : File opening modes in C ].
  3. After opening file in the read mode fopen() will return the address of the structure that contains information needed for subsequent I/O on the file being opened.(i.e File Pointer)
  4. In order to store file pointer we have assigned return address to FILE pointer variable “fp“.
  5. e.g here fopen will open “file1.txt” in the “read” mode.
fp = fopen("file1.txt","r");

Live Example :


void main()
FILE *fp;
char ch;

fp = fopen("INPUT.txt","r"); 

  ch = fgetc(fp); 
  if(ch == EOF ) 
     break ;