NIOS Computer Science: Chapter 16 – Files Part 1

Get unlimited access to the best preparation resource for UGC : fully solved questions with step-by-step explanation- practice your way to success.

Download PDF of This Page (Size: 166K)

Image of file writing and reading

Image of Writing and Reading File

Image of file writing and reading


At times it is required to store data on hard disk or floppy disk in some application program. The data is stored in these devices using the concept of file.


After going through this lesson, you would be able to:

  • store data in a file

  • access data record by record from the file

  • move pointer within the file

  • open or close file


A file is a collection of logically related records. A program usually requires two types of data communication.

Diagram shows types of data communication

Diagram Shows Types of Data Communication

Diagram shows types of data communication

(I) Writing Data on the Data File:

The data flows from keyboard to memory and from memory to storage device.

keyboard memory hard disk/floppy disk

This is called output stream where stream is the flow of data and requires an ofstream.h header file.

(Ii) Reading Data from Data File:

The data flows from storage device to memory and from memory to output device, particularly monitor.

datafile memory output device (screen)

external storage device (hard disk/floppy)

This is called input stream and requires ifstream.h header file.

If both input stream and output stream are used in the same program then header file fstream.h is required.

If header file fstream.h is included in the program, there is no need to include iostream.h explicitly.

Opening a File

A file can be opened in two ways:

(i) Using constructor function of a class.

(ii) Using the member function open ( ) of the class.

Opening a file using constructor function.

The following statement opens the file STU.DAT in output mode, i.e., for writing data on the file.

ofstream outfile (“STU.DAT”);

ofstream is a class available in the compiler file.

outfile is any user defined object.

The statements

outfile < < “TOTAL MARKS” << “\n”;

outfile < < total << “\n”;

are used for writing data on the file. The newline character is used for moving the pointer to the next line.

Similarly, the following statement

ifstream infile (“STU.DAT”);

opens the file “STU.DAT” in input mode, i.e., for reading purpose. The statements

infile >> string;

infile >> number;

read the data from the data file.

Developed by: