Chapter Four I-O
Chapter Four I-O
Injibara University
2015 E.C
1
Outline
Introduction
Stream classes
2
Introduction
A file is a logical collection of record.
Standard input and output in C++ is done through the use of streams.
Streams are generic places to send or receive data. Keyboard, screen, file, network.
There are two variables (among others) defined in <iostream>. cout is used for output, cin for
input.
cout and cin are not key words in the C++ language.
They are variables, instances of classes, that have been declared in <iostream>. cout is a
variable of type ostream. cin is a variable of type istream.
3
Cont.
stream - a sequence of characters.
file (fstream)
iostream -- contains basic information required for all stream I/O operations.
4
File stream classes
ifstream: It is the input file stream class.
Its member function open( ) associates the stream with a specified file in an input mode.
Its member function open( ) associates the stream with a specified file in an output mode.
5
Cont.
Variables are stored in Main Memory/RAM " values are lost when program is finished
executing
To have your program manipulate values stored in a file, they must be input into variables
first.
objects of type ofstream can output (write) values to a file. (like cout).
objects of type ifstream can input (read) values from a file. (like cin).
6
Cont.
The functions associated with fstream are:
open : This associates the stream with a specified file.
7
Opening a file
To input from a file, declare an ifstream variable and open a file by its name
ifstream someFile;
someFile.open(“mydatafile.txt”);
To output to a file, declare an ofstream variable, and open a file by its name.
ofstream anotherFile;
anotherFile.open(“myoutputfile.txt”);
someFile.close();
anotherFile.close();
9
Writing to a file
Use the stream insertion operator: <<
10
Reading from a file
When opened, file stream's read position points to first character in file.
Extraction operator (>>) starts at read position and skips whitespace to read data into the
variable.
The read position then points to whitespace after the value it just read.
11
File types
Text files: plain text files combination of alphabets, digits and symbols.
12
File access methods
Sequential access: the records are accessed sequentially.
13
Advantage of pointers
Pointers are useful in C++ for several reasons
14