Files: Introduction, Objectives, Writing and Reading Data on the Data File, opening a File

Get unlimited access to the best preparation resource for IAS : Get complete video lectures from top expert with unlimited validity: cover entire syllabus, expected topics, in full detail- anytime and anywhere & ask your doubts to top experts.

Download PDF of This Page (Size: 181K)

Image of file writing and reading

Image of Writing and Reading File

Image of file writing and reading

Introduction

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.

Objectives

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

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

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 of stream header file.

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 if stream 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.

of stream outfile (“STU.DAT”);

of stream 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

if stream in file (“STU.DAT”);

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

in file >> string.

in file >> number.

read the data from the data file.

Developed by: