Download as pdf or txt
Download as pdf or txt
You are on page 1of 26

File Streams

Objective

• How to read and write from 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
Why use amounts of input data, and output data
files? 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.
Why use • To achieve this, the data is packaged
files? 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.
Before we can work with files in C++, we need to become
acquainted with the notion of a stream.

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


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.
In fact, input and output streams such as
"cin" and "cout" are examples of (stream)
objects.

So learning about streams is a good way


Streams to introduce some of the syntax and ideas
behind the object-oriented part of C++.

The header file which lists the operations


on streams both to and from files is called
"fstream".
We will therefore assume that the program fragments
discussed below are embedded in programs containing the
"include" statement

Streams #include<fstream>

As we shall see, the essential characteristic of stream


processing is that data elements must be sent to or
received from a stream one at a time, i.e. in serial fashion.
Before we can use an input or output stream in a
program, we must "create" it. Statements to create
streams look like variable declarations, and are usually
placed at the top of programs or function
implementations along with the variable declarations.

Creating Streams

So for example the statements

ifstream ofstream
in_stream; out_stream;
respectively create a stream called "in_stream"
belonging to the class (like type) "ifstream" (input-
file-stream),

and a stream called "out_stream" belonging to


the class "ofstream" (output-file-stream).
Creating Streams
However, the analogy between streams and
ordinary variables (of type "int", "char", etc.) can't
be taken too far.

We cannot, for example, use simple assignment


statements with streams (e.g. we can't just write
"in_stream1 = in_stream2").
There are three new data types in fstream

ofstream
• This data type represents the output file stream and is
used to create files and to write information to files.

ifstream
fstream • This data type represents the input file stream and is
used to read information from files.

fstream
• This data type represents the file stream generally, and
has the capabilities of both ofstream and ifstream
which means it can create files, write information to
files, and read information from files.
Having created a stream, we can connect it to a file
using the member function "open(...)”

Connecting The function "open(...)" has a different effect for


and ifstreams than for ofstreams (i.e. the function is
polymorphic).

Disconnecting To connect the ifstream "in_stream" to the file


Streams to "Lecture_4", we use the following statement:

Files • in_stream.open("Lecture_4");

This connects "in_stream" to the beginning of


"Lecture_4". Diagramatically, we end up in the
following situation:
Connecting and Disconnecting Streams to Files

To connect the ofstream "out_stream" to Although this connects "out_stream" to To disconnect connect the ifstream
the file "Lecture_4", we use an analogous "Lecture_4", it also deletes the previous "in_stream" to whatever file it is
statement: contents of the file, ready for new input. connected to, we write:
out_stream.open("Lecture_4"); in_stream.close();
Connecting THE STATEMENT: OUT_STREAM.CLOSE();

and
Disconnecting
Streams to
Files
HAS A SIMILAR EFFECT, BUT IN IN THIS CASE, THE FILE "LECTURE_4"
ADDITION THE SYSTEM WILL STILL EXISTS, BUT IS EMPTY.
"CLEAN UP" BY ADDING AN "END-
OF-FILE" MARKER AT THE END OF
THE FILE.
Example
This code creates a
file
called example.txt and
inserts a sentence
into it in the same
way we are used to
do with cout, but
using the file
stream myfile instead.
The first operation generally performed
on an object of one of these classes is to
associate it to a real file.

How to Open a
file An open file is represented within a
program by a stream (i.e., an object of
one of these classes; in the previous
This procedure is known as to open a
example, this was myfile) and any input
file.
or output operation performed on this
stream object will be applied to the
physical file associated to it.
In order to open a file with a stream object we use its
member function open:

To Open a file open (filename, mode);

Where filename is a string representing the name of


the file to be opened, and mode is an optional
parameter with a combination of the following flags:
To Open a file
To Open a file

• All these flags can be


combined using the bitwise
operator OR (|). 1 ofstream myfile;
• For example, if we want to 2 myfile.open
open the file example.binin
binary mode to add data ("example.bin",
we could do it by the ios::out | ios::app |
following call to member
function open: ios::binary);
To Open a file

• Each of the open member


functions of
classes ofstream, ifstream and default mode
class
fstream has a default mode parameter
that is used if the file is opened
without a second argument: ofstream ios::out
ifstream ios::in
fstream ios::in | ios::out
For ifstream and ofstream classes, ios::in and ios::out are
automatically and respectively assumed, even if a mode
that does not include them is passed as second argument
to the open member function (the flags are combined).

To Open a For fstream, the default value is only applied if the


function is called without specifying any value for the

file mode parameter.

If the function is called with any value in that parameter


the default mode is overridden, not combined.
File streams opened in binary mode
perform input and output
operations independently of any
format considerations.
To Open a
file Non-binary files are known as text
files, and some translations may
occur due to formatting of some
special characters (like newline and
carriage return characters).
Since the first task that is performed on a file stream is
generally to open a file, these three classes include a
constructor that automatically calls the open member
function and has the exact same parameters as this
member.

To Open a Therefore, we could also have declared the previous


myfile object and conduct the same opening operation in

file our previous example by writing:

ofstream myfile ("example.bin", ios::out | ios::app |


ios::binary);
Combining object construction and stream
opening in a single statement. Both forms to
open a file are valid and equivalent.

To check if a file stream was successful opening


a file, you can do it by calling to member
To Open a is_open.

file This member function returns a bool value of


true in the case that indeed the stream object is
associated with an open file, or false otherwise:

if (myfile.is_open()) { /* ok, proceed with


output */ }
Closing a file
After completing input and output operations on a file it is imperative to close
it so that the operating system is notified and its resources become available
again.

For that, we call the stream's member function close.

myfile.close();
This member function takes flushes the associated buffers and closes the file:
Closing a file

myfile.close();
Once this member function is
In case that an object is destroyed
called, the stream object can be re-
while still associated with an open
used to open another file, and the
file, the destructor automatically
file is available again to be opened
calls the member function close.
by other processes.
Reading from a
file (Example)
• Reading from a file can also be
performed in the same way as was
done with cin:

You might also like