File Handling in C ?


A file is defined as a collection of data stored on the secondary device such as hard disk. An input file contains the same items we might have typed in form the keyboard . An output file contains the same information that might have been sent to the screen as the output from our program.


Steps in using the file

  • Declare a file pointer variable.
  • Open a file
  • Read the data from the file or write the data into the file.
  • Close the file.

Declare a file pointer variable

We know that all the variables are declared before they are used likewise a file pointer variable also should be declared.
A file pointer variable fp should be declared as a pointer to structure of type FILE as.

Example of declaring a file pointer variable.
 #include<stdio.h>
 FILE*fp      /*here, fp is a pointer to a structure FILE */
 void main()
 {
 file operations
 }

File open and close functions

The file should be opened before reading a file or before writing into a file.


Syntax to open a file for either read or write operations.
 #include<stdio.h>
 FILE *fp;     /*here, fp is a pointer to a structure FILE */
 void main()
 {
 ......
 ......
 fp=fopen(char*filename,char*mode);
 }

Where,
fp is a file pointer of type FILE.
filename:- holds the name of the file to be opened. The filename should be identifier.
mode:- may be



Mode of file

  • . Open a text file for reading, this method is used for opening an exiting file to perform read operations
  • w this mode is used to create a file.
  • a append to a text file, this mode is used to insert the data at end of the existing file.