File Handling in C

Subject: Computer Science

Find Your Query


This note is about the File Handling in C used in C programming Language to handle the different files. It explains the communication process of file like open the file, read or write to the file and close the file. It also explains the predefined streams. Streams are constants and not variables.
File Handling in C


In C, a file can refer to a disk file, a terminal, a printer, or a drive. In other words, a file represents a concrete device which you want to exchange information. A file is a region in hard or in auxiliary storage devices. It contains bytes of information.

Before you perform any communication to a file, you have to open a file. At the end, of the process, you need to close the file I/O is always done in a program in the following sequence.

  1. Open the file.
  2. Read or write to the file.
  3. Close the file.

Opening Files

Before performing any file I/O, the file must be opened. While opening the file, the following are specified.

  1. The name of the file.
  2. The manner in which it should be opened (i.e., reading, writing, both reading and writing, appending, overwriting, etc.)

The function of fopen is used to open a file. It accepts two strings, the first is the name of the file, and the second is the mode in which it should be opened.

revamp nepal Abroad Studies Opportunities


FILE *ptvar

Here, File is a special structure type that establishes the buffer area and ptvar is a pointer variable that indicates the beginning of the buffer area. The structure type of FILE is defined within a system include file, typically stdio.h. The pointer ptvar is often referred to as stream pointer or simply a stream.

Example: Opening a file

FILE *fp;

fp = fopen (“outfile1.txt”,”w”);

*fp declares the pointer to the FILE structure. The structure is defined in <stdio.h>.

The function fopen returns a pointer to the FILE structure which it creates. This pointer must be used in subsequent operations on the files, such as reading from or writing to it. The FILE pointer fp, is also said to represent the stream of a file called outfile1.txt already exists, it is deleted and rewritten.

The file can be open in the following manner

File Type








Open an existing file for read only

Open a new file for writing only

Open an existing file for appending data elements

Open an existing file for both reading and writing

Open a new file for both reading and writing

Open an existing file for both reading and appending. A new file will be created if the specified file does not exist

Example: # Enter some characters through the keyboard and write them to the file and finally display them on the monitor.

#include <stdio.h>

#include <conio.h>

void main ()


FILE *f1;

char c;

printf(“Data input\n”);



while ((c=getchar())!EOF)


fclose (f1);

printf(“\n Data output: \n”);

f1=fopen (“input”, “r”);

while ((c=getc(f1))! =EOF)

printf(“%c”, c);

fclose (f1);


Writing to Files

When a file is created in output mode, the data or elements should be written to the disk in a specified file. The specified file has name and extension generally. The writing of the data from a keyboard is carried out by using the following functions.

  1. fwrite

Fwrite appends a specified number of equal-sized data items to an output file.

Syntax: size_t (fwrite const void * ptr,size-t size, size_t n, FILE * stream);

  1. fprintf

The function fprintf writes to the files associate with the file stream.

Syntax: int fprintf(FILE *stream, const char * format [, argument,…., argument]);

Example: # Write a program to accept an integer and save in file outfile.txt

#include <stdio.h>

void main ()


int i;

FILE *fp=fopen (“outfile1.txt”,”w”);

printf(“\n Input an integer:”);

scanf(“%d”, &i);

fprintf(fp, “%d\n”, i);

fclose (fp);


Here, fprintf function writes the variable to the file as printf writes to the screen.

Reading from Files

The function of scanf, gets, getc are used to read from the standard input. To read from a file, the functions fscanf, fgets, and fgetc are used. All these functions accept a FILE pointer (obtained from fopen), as their first parameter, in addition to the parameters required by the standard input functions.

Example 3: # Write a program to open “outfile.txt” in read mode and display its content.

#include <stdio.h>

void main ()


int i;

FILE *fp=fopen (“outfile1.txt”, “r”);

fscanf(fp, “%d”, &i);

printf(“The integer in the outfile is %d”, i);

fclose (fp);


The file handling function used are:



Used as











Individual characters

Character string

Formatted ASCII

Binary files

Low level binary

Example: # Enter a formatted data as name, age, and roll through the keyboard and write them to a file and display them on the monitor.

/* program to write and retrieve records from a file */

/* create a file in write mode */

#include <stdio.h>

typedef struct


char name[50];

unsigned int age;

unsigned int rollno;



void main (void)


st_rec rec;

FILE *fp;

fp=fopen (“class.rec”,”w”);

printf(“\n Enter Name, Age and Roll Number separated with space \n”);

printf(“\n type Ctrl+Z to stop \n”);

/* read form keyboard and write to file */

while ((scanf(“%s %u”,, &rec.age, &rec.rollno))!=EOF)

fwrite(&rec, sizeof (rec), 1, fp);

fclose (fp);


/* read form file and write on screen */

fp=fopen (“class.rec”, “r”);

/*while (fread (&rec, sizeof (rec), 1, fp))

printf(“%-10s %5u %3u\n”,, rec.age, rec.rollno);

fclose (fp);


Predefined Streams

When a C program begins execution, the following data streams (pointer to FILE structures) will be automatically opened (these files are constants and not variables).






opening input device

open for output device

open for error output device

open for an auxiliary device (I/O)

open printer for output

Closing Files

During a write to a file, the data written is not put on the disk immediately. It is stored in a buffer. When the buffer is full, all its contents are actually written to the disk. The process of emptying the buffer by writing its contents to the disk is called flushing the buffer.

Closing the file flushes the buffer and releases the space taken by the FILE structure which is returned by fopen. If a particular FILE pointer is not required after a certain point in a program, pass it to the fclose and close the file.

#Write a program to demonstrate opening a file in append mode, read and write a file.

/* file handling in append mode, read and write to a file */

#include <stdio.h>

void main ()


FILE *fp

char name[20];

unsigned int mark;

/* file STUREC is open in append mode */



printf(“Use Ctrl+D or Ctrl+Z to stop entry\n”);

printf(“Enter name and space bar and mark”);

while ((scanf(“%s %u”, name, &mark))!=EOF)

/* writing student name to file STUREC*/

fprintf(fp, “%s %u”, name, mark);

fclose (fp);


/* opening the file for read mode */


printf(“ NAME MARK \n”);


while ((fscanf(fp, “%s %u”, name, &mark ))!=EOF)

/* display file content */

printf(“%+10s %3u \n”, name, mark);

fclose (fp);


# Write a program to write student reg_no, name and mark into a data file and read from it.

/*program to write and retrieve records from a file */

/* create a file in write mode */

#include <stdio.h>

typedef struct


unsigned int reg_no;

char name[50];

unsigned int mark;



void main (void)


st_rec rec;

FILE *fp;

fp=fopen (“class.rec”,”w”);

printf(“\n Enter register number, name and mark separated with space \n”);

printf(“\n type Ctrl+Z to stop \n”);

/* read from keyboard and write to file */

while (( scanf(“%u %s %u”, &rec.regno,, &rec.mark))!=EOF)

fwrite (&rec, sizeof (rec), 1, fp);

fclose (fp);


/* read from file and write on screen */

fp=fopen (“class.rec”,”r”);

/* while loop terminates when fread return 0 */

while (fread (&rec, sizeof (rec), 1, fp))

printf(“%5u, %-10s %3u\n”, rec.reg_no,, rec.mark);

fclose (fp);




Khanal, R.C. Khanal, R.C. Computer Concept for XII. Pashupatigriha Marga, Thapathali, Kathmandu, Nepal: Ekta Books Distributors Pvt. Ltd., 2010. 281-285.

Things to remember
  • The file is a region of storage in hard disks or in auxiliary storage devices. It contains bytes of information. It is not a data type.
  • The header file stdio.h is necessary for file handling because the required functions, definitions and declarations are available in it. It should be included using preprocessor definitions.
  • The action of connecting a program to a file is called opening of that file. This requires creating an I/O stream before reading or writing the data.
  • FILE is a word which refers to a predefined data type. It is defined in stdio.h file. A file pointer points to the back of information of the stream that has just been opened.
  • Two levels of files are there: High-level file (steam-oriented) and Low-level files (system files). Directives (#) are preprocessor control lines that control the preprocessor facilities. They start with # sign.


  • It includes every relationship which established among the people.
  • There can be more than one community in a society. Community smaller than society.
  • It is a network of social relationships which cannot see or touched.
  • common interests and common objectives are not necessary for society.

© 2019-20 Kullabs. All Rights Reserved.