Home C Programming Tutorial C Programming File Handling

C Programming File Handling

by anupmaurya
8 minutes read

In this article, you will learn about File Handling in C programming.

File handling in C refers to the task of storing data in the form of input or output produced by running C programs in data files, namely, a text file or a binary file for future reference and analysis.

The operations that you can perform on a File in C are −

  • Creating a new file
  • Opening an existing file
  • Reading data from an existing file
  • Writing data to a file
  • Moving data to a specific location on the file
  • Closing the file

Functions for file handling

There are many functions in the C library to open, read, write, search and close the file. A list of file functions are given below:

1fopen()opens new or existing file
2fprintf()write data into the file
3fscanf()reads data from the file
4fputc()writes a character into the file
5fgetc()reads a character from file
6fclose()closes the file
7fseek()sets the file pointer to given position
8fputw()writes an integer to file
9fgetw()reads an integer from file
10ftell()returns current position
11rewind()sets the file pointer to the beginning of the file

1. File Pointers

There are many ways to use files in C. The most straightforward use of files is via a file pointer.

FILE *fp; 

fp is a pointer to a file.

The type FILE, is not a basic type, instead, it is defined in the header file stdio.h, this file must be included in your program.

2. Opening a File

fp = fopen(filename, mode);

The filename and mode are both strings.

We can use one of the following modes in the fopen() function.

ropens a text file in read mode
wopens a text file in write mode
aopens a text file in append mode
r+opens a text file in read and write mode
w+opens a text file in read and write mode
a+opens a text file in read and write mode
rbopens a binary file in read mode
wbopens a binary file in write mode
abopens a binary file in append mode
rb+opens a binary file in read and write mode
wb+opens a binary file in read and write mode
ab+opens a binary file in read and write mode

The following useful table from the ANSI C Rationale lists the different actions and requirements of the different modes for opening a file:

file handling in C programming
file handling in C programming

fopen returns NULL if the file could not be opened in the mode requested. The returned value should be checked before any attempt is made to access the file. The following code shows how the value returned by fopen might be checked. When the file cannot be opened a suitable error message is printed and the program halted. In most situations this would be inappropriate, instead the user should be given the chance of re-entering the file name.

#include <stdio.h>
int main()
    char filename[80];
    FILE *fp;
    printf("File to be opened? ");
    scanf("%79s", filename);
    fp = fopen(filename,"r");
    if (fp == NULL)
        fpri ntf(stderr, "Unable to open file %s\n", filename);
        return 1; /* Exit to operating system */
    //code that accesses the contents of the file
    return 0;

3.Closing File: fclose()

The fclose() function is used to close a file. The file must be closed after performing all the operations on it. The syntax of fclose() function is given below:

  1. int fclose( FILE *fp ); 


Program to Open a File, Read from it, And Close the File

// C program to Open a File,
// Read from it, And Close the File

# include <stdio.h>
# include <string.h>

int main( )

	// Declare the file pointer
	FILE *filePointer ;
	// Declare the variable for the data to be read from file
	char dataToBeRead[50];

	// Open the existing file GfgTest.c using fopen()
	// in read mode using "r" attribute
	filePointer = fopen("GfgTest.c", "r") ;
	// Check if this filePointer is null
	// which maybe if the file does not exist
	if ( filePointer == NULL )
		printf( "GfgTest.c file failed to open." ) ;
		printf("The file is now opened.\n") ;
		// Read the dataToBeRead from the file
		// using fgets() method
		while( fgets ( dataToBeRead, 50, filePointer ) != NULL )
			// Print the dataToBeRead
			printf( "%s" , dataToBeRead ) ;
		// Closing the file using fclose()
		fclose(filePointer) ;
		printf("Data successfully read from file GfgTest.c\n");
		printf("The file is now closed.") ;
	return 0;		

Sequential file access is performed with the following library functions.

  • fprintf(fp, formatstring , ...) – print to a file
  • fscanf(fp, formatstring , ...) – read from a file
  • getc(fp) – get a character from a file
  • putc(c, fp) – put a character in a file
  • ungetc(c, fp) – put a character back onto a file (only one character is guaranteed to be able to be pushed back)
  • fopen( filename , mode) – open a file
  • fclose(fp) – close a file

The standard header file stdio.h defines three file pointer constants, stdin ,stdout and stderr for the standard input, output and error streams. It is considered good practice to write error messages to the standard error stream.

Use the fprintf() function to do this:

fprintf(stderr,"ERROR: unable to open file %s\n", filename);

The functions fscanf() and getc() are used for sequential access to the file, that is subsequent reads will read the data following the data just read, and eventually you will reach the end of the file. If you want to move forwards and backwards through the file, or jump to a specific offset from the beginning, end or current location use the fseek() function (though the file mustbe opened in binary mode). The function ftell() reports the current offset from the beginning of the file.

If you wish to mix reading and writing to the same file, each switch from reading to writing (or vice versa) mustbe preceded by a call to fseek()fsetpos()rewind() or fflush(). If it is required to stay at the same position in the file then use fflush() or fseek(fp,0L,SEEK_CUR) which will move 0 bytes from the current position!

Hope you like this article in File Handling. Please Share with your friends!

You may also like

Adblock Detected

Please support us by disabling your AdBlocker extension from your browsers for our website.