Lesson 21
Lesson 21
Programming in C++
21
FILES Notes
In the previous lesson you have learnt about pointers. Now, you will learn about
files. In some application program, sometimes it is required to store data on
hard disk or any other storage devices. The data is stored in these devices using
the concept of file. In this lesson you will learn to store data in a file, access
data from a file, move pointer within the file.
OBJECTIVES
After reading this lesson, you will be able to:
z store data in a file;
z access data record by record from the file;
z move pointer within the file;
z open or close file.
21.1 FILE
A file is a collection of logically related records. A program usually requires two
types of data communication, (i) writing data on datafile, (ii) reading data from
datafile.
Let us learn about them.
(i) Writing data on the datafile:
The data flows from keyboard to memory and from memory to storage device.
i.e., keyboard → memory → hard disk/ storage device
This is called output stream where stream is the flow of data and requires an
ofstream.h header file.
Notes
Parameter Meaning
ios : : app It opens the file in output mode. The file pointer is at
the end of file and it can add a record.
Notes
ios :: ate The file pointer is at the end of the file and it allows
to add data or to modify the existing data anywhere in
the file.
ios :: nocreate If file is already present, it opens the file otherwise open
fails.
ios :: noreplace If file is not present, it opens the file otherwise open
statement fails.
ios :: out It opens the file in output mode. The file pointer is at
the end of the file. If it already has a data, the output
mode erases the content of the file.
The mode can combine two or more parameters using bitwise OR operator.
Example:
File has two associated pointers called input pointer (or get pointer) and output
pointer (or put pointer). Each time an input or output operation takes place,
the pointer moves automatically. There are two pointers.
↑ ↑ ↑
ios :: beg ios :: cur ios :: end
ios :: beg – means beginning of the file.
ios :: cur – means current position of the pointer
ios :: end – means end of the file
The seekg ( ) and seekp ( ) statement has two parameters.
object . seekg (no. of bytes, refposition);
object . seekp (no. of bytes, refpostion);
The refposition takes one of the above three constants defined in the ios class.
Example 1
infile.seekg (0, ios::beg);
It moves the pointer to the beginning of the file. In this case, the refposition
ios :: beg is optional.
infile.seekg ( 100, ios::cur);
It moves the pointer 100 bytes forward from the current position.
infile.seekg (-200, ios::end);
It moves the pointer 200 bytes backward from the end of the file.
21.1
1. (a) file (b) output
(c) input (d) open
(e) output (f) trunc