Unit V: Files and Streams
Introduction
• In C++, input and output is performed in the form of a sequence of bytes or
streams.
• C++ comes with libraries which provides many ways for performing input and
output.
Input Stream:
Flow of bytes from input device to main memory.
Output Stream:
Main memory to display screen.
File Input Output Streams
Consol Program File Interaction
Types of Streams
1. Text Stream
• It is a collection of sequences of characters. Character translation may be done in a text
stream, but in a binary stream, translation cannot be done.
• For example, a new line may be converted to a carriage return/line feed pair It means that
there may not be a one-to-one relationship between the written characters and the characters
in an external device.
2. Binary Stream
• It is a sequence of bytes.
• In the binary stream, translation is not done.
• It exists with one-to-one correspondence with external devices.
• The number of bytes can be written or read as the same as the number of bytes on the
external device. However, an Implementation-defined number of bytes may be appended to a
binary stream.
File Input and Output Stream
Text Stream Vs Binary Stream
Stream Classes
In C++ there are number of stream classes for defining various streams related with files and for doing input-output
operations. All these classes are defined in the file iostream.h. Figure given below shows the hierarchy of these classes.
Stream Classes
1. ios class is topmost class in the stream classes hierarchy. It is the base class for istream,
ostream, and streambuf class.
2. istream and ostream serves the base classes for iostream class. The class istream is used for input and ostream for
the output.
3. Class ios is indirectly inherited to iostream class using istream and ostream. To avoid the duplicity of data and
member functions of ios class, it is declared as virtual base class when inheriting in istream and ostream
4. The _withassign classes are provided with extra functionality for the assignment operations that’s
why _withassign classes.
Facilities Provided by Stream Classes
1. The ios class: The ios class is responsible for providing all input and output facilities to all other
stream classes.
2. The istream class: This class is responsible for handling input stream. It provides number of
function for handling chars, strings and objects such as get, getline, read, ignore, putback etc.
3. The ostream class: This class is responsible for handling output stream. It provides number of
function for handling chars, strings and objects such as write, put etc.
4. The iostream: This class is responsible for handling both input and output stream as both istream
class and ostream class is inherited into it. It provides function of both istream class and ostream
class for handling chars, strings and objects such as get, getline, read, ignore, putback, put,
write etc.
5. istream_withassign class: This class is variant of istream that allows object assignment. The
predefined object cin is an object of this class and thus may be reassigned at run time to a
different istream object.
Header files available in C++ for Input / Output operations
• iostream: iostream stands for standard input-output stream. This header file contains
definitions of objects like cin, cout, cerr, etc.
• iomanip: iomanip stands for input-output manipulators. The methods declared in these
files are used for manipulating streams. This file contains definitions of setw,
setprecision, etc.
• fstream: This header file mainly describes the file stream. This header file is used to
handle the data being read from a file as input or data being written into the file as
output.
Built in streams
The two instances cout and cin in C++ of iostream class are used very often for printing outputs and taking
inputs respectively.
These two are the most basic methods of taking input and printing output in C++. To use cin and cout in C++
one must include the header file iostream in the program.
• Standard output stream (cout): Usually the standard output device is the display screen. The
C++ cout statement is the instance of the ostream class. It is used to produce output on the standard output
device which is usually the display screen. The data needed to be displayed on the screen is inserted in the
standard output stream (cout) using the insertion operator(<<).
• Standard input stream (cin): Usually the input device in a computer is the keyboard. C++ cin statement is
the instance of the class istream and is used to read input from the standard input device which is usually a
keyboard.
The extraction operator(>>) is used along with the object cin for reading inputs. The extraction operator
extracts the data from the object cin which is entered using the keyboard.
• Un-buffered standard error stream (cerr): The C++ cerr is the standard error stream that is used to output
the errors. This is also an instance of the iostream class. As cerr in C++ is un-buffered so it is used when one
needs to display the error message immediately. It does not have any buffer to store the error message and
display it later.
Example: cerr
Buffered standard error stream (clog-character logging):
Buffered standard error stream (clog):
This is also an instance of ostream class and used to display errors but unlike cerr the error is first inserted into a buffer and
is stored in the buffer until it is not fully filled or the buffer is not explicitly flushed (using flush()). The error message will
be displayed on the screen too.
Stream Errors
Stream status flag
Error status bit and functions for Error flag
Inputing numbers
Too many characters
No Input Output
Disk File I/O with Streams: Opening and Closing Files
When you open a file in C++, you must first obtain a stream. There are the following three types of
streams:
input
output
input/output
Create an input stream
• To create an input stream, you must declare the stream to be of class ifstream. Here is the syntax:
• Create an output stream
To create an output stream, you must declare it as a class ofstream. Here is an example:
Opening and Closing Files
Create input and output streams
Streams that will be performing both input and output operations must be declared
as class fstream. Here is an example:
Opening of Files
Once a stream has been created, the next step is to associate a file with
it. Following that, the file is ready (opened) for processing.
The opening of files can be achieved in the following two ways:
1. Using the constructor function of the stream class
2. Using the function open()
The first method is preferred when a single file is used with a stream.
However, for managing multiple files with the same stream, the second
method is preferred. Let's discuss each of these methods one by one.
Opening a File Using Constructors
• Constructor of a class initializes an object of its class when it is being created.
• In the same way, the constructors of stream classes (ifstream, ofstream, or fstream) are used to
initialize file stream objects with the filenames passed to them.
• To open a file named myfile as an input file (data will be required from it and no other operations
such as writing or modifying will be performed on the file),
• we will create a file stream object of input type, i.e., an ifstream type. Here is an example:
ifstream fin("myfile", ios::in) ;
• The preceding statement creates a "fin" object from an input file stream.
• The object name is a user-defined name (i.e., any valid identifier name can be given).
• After creating the ifstream object fin, the file myfile is opened and attached to the input stream, fin.
• Now, both sets of data being read from myfile have been channeled through the input stream object.
Opening a File Using Constructors
ofstream outfile(“results”);
ifstream infile (“data”;)
Two file streams working on one file
ofstream outfile(“salary”);
ifstream infile (“salary”;)
Opening a File
• The connections with a file are closed automatically when the input
and output stream objects expire, i.e., when they go out of scope.
• For example, a global object expires when the program terminates.
• We can explicitly close a connection with a file by using the close()
method.
Opening Files using open()
• The function open() can be used to open multiple files that use the
same stream object.
• Eg. We want to process a set of files sequentially. We can do it using
open() function.
• In that case, we may create a single stream object and use it to open
each file in turn.
file-stream-class stream-object ;
stream-object.open (“filename”) ;
Opening Files using open()
file-stream-class stream-object ;
stream-object.open (“filename”) ;
Example:
ofstream outfile;
outfile.open(“DATA1”);
………
outfile.close();
outfile.open(“DATA2”);
……………
outfile.close();
Working with Multiple Files
Detecting End-of-file
• Necessary for prevention of an attempt to read data from file.
• First approach is by using fin() function as :
while(fin)
But this loop may terminate due to other failures as well.
• Second approach is by using eof() which is member function of ios class .
It returns a non-zero value if end-of-file(EOF) condition is encountered.
File modes
File Pointers and Their Manipulations
• Each file has two associated pointers known as file pointers.
• One is called input pointer (or get pointer) & other is called output
pointer (or put pointer).
• Used to move through files while reading or writing.
• Input pointer is used to read contents of file location and Output
pointer is used to write to a file location.
• Each time I/O operation takes place and appropriate pointer is
automatically advanced.
Default Actions
Functions for Manipulation of File Pointers
• seekg() : Moves get pointer (input) to a specified location.
• seekp() : Moves put pointer (output) to a specified location.
• tellg() : Gives the current position of get pointer
• tellp() : Gives the current position of put pointer
• Eg. :
infile.seekg(10) ;
It moves the file pointer to byte number 10.
Specifying the offset
Sequential Input and Output Operations
put() and get() functions
• put() and get() are designed for handling a single character at a time.
• put() : This function writes a single character to the associated stream.
• get() : This function reads a single character from the associated
stream.
Sequential Input and Output Operations
write() and read() functions
• write() and read() functions handle the data in binary form.
• The binary input and output functions write() and read() are designed
to support writing to and reading from the disk file objects directly.
Error Handling During File Operations
The following things may happen if we get an error when dealing with
files:
• A file which we are attempting to open for reading does not exist.
• The file name used for a new file may already exist.
• We may attempt an invalid operation such as reading past the end-of-
file.
• There may not be any space in the disk for storing more data.
• We may use an invalid file name
• We may attempt to perform an operation when the file is not opened
for that purpose
Error Handling During File Operations
• Error handling functions are given below
File I/O with Member Functions
• File Input/Output (I/O) is a crucial aspect of programming that
involves reading data from and writing data to files.
• Enables the storage and retrieval of data beyond the program's
execution, providing a persistent storage solution.
C++ Member Functions for File I/O:
• ofstream: For writing to files (Output File Stream).
• ifstream: For reading from files (Input File Stream).
• fstream: For both reading and writing (File Stream).
What is Operator Overloading?
• Operator overloading is a feature in C++ that allows you to redefine
the behavior of existing operators for user-defined data types.
• Enhances the readability and usability of user-defined classes by
extending the functionality of operators.
• Commonly Overloaded Operators:
• Arithmetic operators (+, -, *, /)
• Comparison operators (==, !=, <, >)
• Stream insertion (<<) and extraction (>>) operators
Overloading the extraction and insertion
operators
Overloading the Insertion Operator (<<)
• The stream insertion operator (<<) is commonly used for displaying
object content.
• The overloaded operator is declared as a friend function to access the
private members of the class.
Overloading the Extraction Operator (>>) Operator
• The stream extraction operator (>>) is used for reading input into an
object.
• The overloaded operator is declared as a friend function to access the
private members of the class
Memory as a Stream Object
Introduction
• Treating a block of memory as a stream enables input and output
operations similar to file or console streams.
• Useful when you want to manipulate data in memory without
necessarily interacting with files or user input/output.
• Memory Stream Class:
In C++, the std::stringstream class from the <sstream> header is
commonly used for this purpose
Memory as a Stream Object
• Creating a memory stream(Syntax)
#include <sstream>
std::stringstream memoryStream;
Operations:
• memoryStream.str(): Get the content as a string.
• memoryStream << "Data": Insert data into the stream.
• memoryStream >> variable: Extract data from the stream.
Memory as a Stream Object
Syntax:
#include <iostream>
#include <sstream>
int main() {
std::stringstream memoryStream;
memoryStream << "Hello, Memory Stream!";
std::cout << "Content: " << memoryStream.str() << std::endl;
return 0;
}
Memory as a Stream Object
Reading and Writing to Memory Stream
• Reading:
Syntax:
std::string data;
memoryStream >> data;
• Writing:
Syntax:
memoryStream << "New Data";
Command Line Arguments
• Command line arguments are values provided to a program when it is
executed from the command line or terminal.
• In C++, the main function can accept two parameters: argc (argument
count) and argv (argument vector).
• argc: Number of arguments provided (including the program name).
• argv: Array of strings containing the actual arguments.
main(int argc, char* argv[])
Printing Output
• In C++, the cout stream is used to print output to the console.
• Use << to concatenate variables with the cout stream.
• cout is part of the <iostream> library.
Syntax:
#include <iostream>
int main() {
std::cout << "Hello, World!" << std::endl;
return 0;
}
Thank You