C++ Files and Streams
C++ Files and Streams
C++ Files and Streams
Mujeeb Rahman K
Asstnt Professor
MES KVM College Valanchery
Why Use Files?
All the programs we have looked at so far use input only from the
keyboard, and output only to the screen.
If we were restricted to use only the keyboard and screen as input
and output devices, it would be difficult to handle large amounts
of input data, and output data would always be lost as soon as we
turned the computer off.
To avoid these problems, we can store data in some secondary
storage device, usually magnetic tapes or discs.
Data can be created by one program, stored on these devices, and
then accessed or modified by other programs when necessary.
To achieve this, the data is packaged up on the storage devices as
data structures called files.
The easiest way to think about a file is as a linear
sequence of characters.
In a simplifed picture (which ignores special
characters for text formatting) these lecture notes
might be stored in a file called "Lecture_4" as:
Streams
We can think of a stream as a channel or conduit on
which data is passed from senders to receivers.
As far as the programs we will use are concerned,
streams allow travel in only one direction.
Data can be sent out from the program on an output
stream, or received into the program on an input stream.
For example, at the start of a program, the standard
input stream "cin" is connected to the keyboard and the
standard output stream "cout" is connected to the
screen.
So far, we have been using the iostream standard
library, which provides cinand cout methods for
reading from standard input and writing to
standard output respectively.
how to read and write from a file?
This requires another standard C++ library
called fstream, which defines three new data
types:
To perform file processing in C++, header files <iostream> and <fstream> must be
included in your C++ source file.
Opening a File:
Here, the first argument specifies the name and location of the file to be
opened and the second argument of the open() member function defines the
mode in which the file should be opened.
You can combine two or more of these values
by OR ing them together.
For example if you want to open a file in write
mode and want to truncate it in case it already
exists, following will be the syntax:
ofstream outfile;
outfile.open("file.dat", ios::out | ios::trunc );
Similar way, you can open a file for reading and writing purpose as
follows:
fstream afile;
afile.open("file.dat", ios::out | ios::in );
Closing a File