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 ?
- fopen opens a stream
- fopen open a file and associate a stream with it.
- functions return a pointer that identifies the stream in subsequent operations.
- FILE will be opened for following purposes -
- Reading data file
- Writing on data file
- Appending Content to the file
Explanation :
- In simple words fopen function will open file specified in the specified mode.
- We have different file opening modes in C Programming. [ Refer : File opening modes in C ].
- 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)
- In order to store file pointer we have assigned return address to FILE pointer variable “fp“.
- e.g here fopen will open “file1.txt” in the “read” mode.
fp = fopen("file1.txt","r");
Live Example :
#include<stdio.h> void main() { FILE *fp; char ch; fp = fopen("INPUT.txt","r") while(1) { ch = fgetc(fp); if(ch == EOF ) break ; printf("%c",ch); } fclose(fp); }