Professional Documents
Culture Documents
UNIT-5: Department of Computer Science & Engineering
UNIT-5: Department of Computer Science & Engineering
Technology
Wardha Road, Nagpur-441 108
NAAC Accredited Grade A+
Approved by AICTE, New Delhi, Govt. of Maharashtra & Affiliated to RTM Nagpur
University, Nagpur
UNIT-5
Basics of I/O Streams and File I/O This is like a cheat sheet for file I/O in C++. It summarizes the steps you
must take to do basic I/ O to and from files, with only a tiny bit of explanation. It is not a replacement for
reading a thorough explanation of file streams in C++. Streams: A stream is a flow of characters.∙ An
input stream is a flow of characters into the program.∙ An output stream is a flow of characters out of
the program.∙ cin is a predefined input stream (defined in∙ ). cout is a predefined output stream
(defined in∙ ). cerr is a predefined output error stream (defined in∙ ), to which you should send all error
messages. It defaults to the terminal (just like cout. ) Streams are defined in the streams library header
file,∙ and implemented in the iostream library.
Creating/Opening a File
There are few important functions to be used with file streams like:
Syntax: filepointer.tellp()
Syntax: filepointer.tellg()
1 ofstream
This data type represents the output file stream and is used to create files
and to write information to files.
2 ifstream
This data type represents the input file stream and is used to read
information from files.
3 fstream
Tulsiramji Gaikwad-Patil College of Engineering and
Technology
Wardha Road, Nagpur-441 108
NAAC Accredited Grade A+
Approved by AICTE, New Delhi, Govt. of Maharashtra & Affiliated to RTM Nagpur
University, Nagpur
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.
To perform file processing in C++, header files <iostream> and <fstream> must be
included in your C++ source file.
Opening a File
A file must be opened before you can read from it or write to it.
Either ofstream or fstream object may be used to open a file for writing. And ifstream
object is used to open a file for reading purpose only.
Following is the standard syntax for open() function, which is a member of fstream,
ifstream, and ofstream objects.
void open(const char *filename, ios::openmode mode);
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.
1 ios::app
Append mode. All output to that file to be appended to the end.
2 ios::ate
Open a file for output and move the read/write control to the end of the file.
Tulsiramji Gaikwad-Patil College of Engineering and
Technology
Wardha Road, Nagpur-441 108
NAAC Accredited Grade A+
Approved by AICTE, New Delhi, Govt. of Maharashtra & Affiliated to RTM Nagpur
University, Nagpur
3 ios::in
Open a file for reading.
4 ios::out
Open a file for writing.
5 ios::trunc
If the file already exists, its contents will be truncated before opening the
file.
You can combine two or more of these values by ORing them together. For example if
you want to open a file in write mode and want to truncate it in case that 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
When a C++ program terminates it automatically flushes all the streams, release all the
allocated memory and close all the opened files. But it is always a good practice that a
programmer should close all the opened files before program termination.
Following is the standard syntax for close() function, which is a member of fstream,
ifstream, and ofstream objects.
Tulsiramji Gaikwad-Patil College of Engineering and
Technology
Wardha Road, Nagpur-441 108
NAAC Accredited Grade A+
Approved by AICTE, New Delhi, Govt. of Maharashtra & Affiliated to RTM Nagpur
University, Nagpur
void close();
Writing to a File
While doing C++ programming, you write information to a file from your program using
the stream insertion operator (<<) just as you use that operator to output information to
the screen. The only difference is that you use an ofstream or fstream object instead of
the cout object.
int main () {
char data[100];
// again read the data from the file and display it.
infile >> data;
cout << data << endl;
return 0;
}
Tulsiramji Gaikwad-Patil College of Engineering and
Technology
Wardha Road, Nagpur-441 108
NAAC Accredited Grade A+
Approved by AICTE, New Delhi, Govt. of Maharashtra & Affiliated to RTM Nagpur
University, Nagpur
When the above code is compiled and executed, it produces the following sample input
and output −
$./a.out
Writing to the file
Enter your name: Zara
Enter your age: 9
Reading from the file
Zara
9
Above examples make use of additional functions from cin object, like getline() function
to read the line from outside and ignore() function to ignore the extra characters left by
previous read statement.
The file-position pointer is an integer value that specifies the location in the file as a
number of bytes from the file's starting location. Some examples of positioning the "get"
file-position pointer are −
// position to the nth byte of fileObject (assumes ios::beg)
fileObject.seekg( n );
Streams
C/C++ IO are based on streams, which are sequence of bytes flowing in and out of the programs (just
like water and oil flowing through a pipe). In input operations, data bytes flow from an input source (such
as keyboard, file, network or another program) into the program. In output operations, data bytes flow
from the program to an output sink (such as console, file, network or another program). Streams acts as
an intermediaries between the programs and the actual IO devices, in such the way that frees the
programmers from handling the actual devices, so as to archive device independent IO operations.
Tulsiramji Gaikwad-Patil College of Engineering and
Technology
Wardha Road, Nagpur-441 108
NAAC Accredited Grade A+
Approved by AICTE, New Delhi, Govt. of Maharashtra & Affiliated to RTM Nagpur
University, Nagpur
C++ provides both the formatted and unformatted IO functions. In formatted or high-level IO, bytes are
grouped and converted to types such as int, double, string or user-defined types. In unformatted or
low-level IO, bytes are treated as raw bytes and unconverted. Formatted IO operations are supported
via overloading the stream insertion (<<) and stream extraction (>>) operators, which presents a
consistent public IO interface.
cin << number; // flush output buffer so as to show the prompting message
1.7 The istream class
Similar to the ostream class, the istream class is a typedef to basic_istream<char>. It also supports
formatted input and unformatted input.
● In formatting input, via overloading the >> extraction operator, it converts the text form (a stream of
character) into internal representation (such as 16-/32-bit int, 64-byte double).
● In unformatting input, such as get(), getlin(), read(), it reads the characters as they are, without
conversion.
Formatting Input via the Overloaded Stream Extraction >> Operator
The istream class overloads the extraction >> operator for each of the C++ fundamental types
(char, unsigned char, signed char, short, unsigned short, int, unsigned int, long, unsigned
long, long long (C++11), unsigned long long (C++11), float, double and long double. It performs
formatting by converting the input texts into the internal representation of the respective types.
istream & operator<< (type &) // type of int, double etc.
The >> operator returns a reference to the invokind istream object. Hence, you can
concatenate >> operations, e.g., cin >> number1 << number2 <<....
The >> operator is also overloaded for the following pointer types:
Tulsiramji Gaikwad-Patil College of Engineering and
Technology
Wardha Road, Nagpur-441 108
NAAC Accredited Grade A+
Approved by AICTE, New Delhi, Govt. of Maharashtra & Affiliated to RTM Nagpur
University, Nagpur
● const char *, const signed char *, const unsigned char *: for inputting C-strings. It uses
whitespace as delimiter and adds a terminating null character to the C-string.
[TODO] Read "C-string input".
Flushing the Input Buffer - ignore()
You can use the ignore() to discard characters in the input buffer:
istream & ignore (int n = 1, int delim = EOF);
// Read and discard up to n characters or delim, whichever comes first
// Examples
cin.ignore(numeric_limits<streamsize>::max()); // Ignore to the end-of-file
cin.ignore(numeric_limits<streamsize>::max(), '\n'); // Ignore to the end-of-line
1.8 Unformatted Input/Output Functions
put(), get() and getline()
The ostream's member function put() can be used to put out a char. put() returns the
invoking ostream reference, and thus, can be cascaded. For example,
// ostream class
ostream & put (char c); // put char c to ostream
// Examples
cout.put('A');
cout.put('A').put('p').put('p').put('\n');
cout.put(65);
// istream class
// Single character input
int get ();
// Get a char and return as int. It returns EOF at end-of-file
istream & get (char & c);
// Get a char, store in c and return the invoking istream reference
// C-string input
istream & get (char * cstr, streamsize n, char delim = '\n');
// Get n-1 chars or until delimiter and store in C-string array cstr.
// Append null char to terminate C-string
// Keep the delim char in the input stream.
istream & getline (char * cstr, streamsize n, char delim = '\n');
// Same as get(), but extract and discard delim char from the
// input stream.
Tulsiramji Gaikwad-Patil College of Engineering and
Technology
Wardha Road, Nagpur-441 108
NAAC Accredited Grade A+
Approved by AICTE, New Delhi, Govt. of Maharashtra & Affiliated to RTM Nagpur
University, Nagpur
// Examples
int inChar;
while ((inChar = cin.get()) != EOF) { // Read till End-of-file
cout.put(inchar);
}
[TODO] Example
read(), write() and gcount()
// istream class
istream & read (char * buf, streamsize n);
// Read n characters from istream and keep in char array buf.
// Unlike get()/getline(), it does not append null char at the end of input.
// It is used for binary input, instead of C-string.
streamsize gcount() const;
// Return the number of character extracted by the last unformatted input
operation
// get(), getline(), ignore() or read().
// ostream class
ostream & write (const char * buf, streamsize n)
// Write n character from char array.
// Example
[TODO]
Other istream functions - peek() and putback()
char peek ();
//returns the next character in the input buffer without extracting it.
cout << "|" << -123456789 << "|" << endl; // |-123456789|
● For floating-point numbers, the default precison is 6 digits, except that the trailing zeros will not be
shown. This default precision (of 6 digits) include all digits before and after the decimal point, but
exclude the leading zeros. Scientific notation (E-notation) will be used if the exponent is 6 or more
or -5 or less. In scientific notation, the default precision is also 6 digits; the exponent is displayed in
3 digits with plus/minus sign (e.g., +006, -005). For example,
● cout << "|" << 1.20000 << "|" << endl; // |1.2| (trailing zeros not displayed)
● cout << "|" << 1.23456 << "|" << endl; // |1.23456| (default precision is 6
digits)
● cout << "|" << -1.23456 << "|" << endl; // |-1.23456|
● cout << "|" << 1.234567 << "|" << endl; // |1.23457|
● cout << "|" << 123456.7 << "|" << endl; // |123457|
Tulsiramji Gaikwad-Patil College of Engineering and
Technology
Wardha Road, Nagpur-441 108
NAAC Accredited Grade A+
Approved by AICTE, New Delhi, Govt. of Maharashtra & Affiliated to RTM Nagpur
University, Nagpur
● cout << "|" << 1234567.89 << "|" << endl; // |1.23457e+006| (scientific-notation
for e>=6)
● cout << "|" << 0.0001234567 << "|" << endl; // |0.000123457| (leading zeros not
counted towards precision)
cout << "|" << 0.00001234567 << "|" << endl; // |1.23457e-005| (scientific-notation
for e<=-5)
● bool values are displayed as 0 or 1 by default, instead of true or false.
Field Width (setw), Fill Character (setfill) and Alignment (left|right|internal)
The ios_base superclass (included in <iostream> header) maintains data members for field-width
(width) and formatting flags (fmtflags); and provides member functions (such as width(), setf()) for
manipulating them.
However, it is more convenience to use the so-called IO manipulators, which returns a reference to the
invoking stream object and thus can be concatenated in << operator (e.g., cout << setfill(':') <<
left << setw(5) <<...). They are:
● setw() manipulator (in <iomanip> header) to set the field width.
● setfill() manipulator (in <iomanip> header) to set the fill character
● left|right|internal manipulator (in <iostream> header) to set the text alignment.
The default field-width is 0, i.e., just enough space to display the value. C++ never truncates data, and
will expand the field to display the entire value if the field-width is too small. The setw() operation
is non-sticky. That is, it is applicable only to the next IO operation, and reset back to 0 after the operation.
The field-width property is applicable to both output and input operations.
Except setw(), all the other IO manipulators are sticky, i.e., they take effect until a new value is set.
// Test setw() - need <iomanip>
cout << "|" << setw(5) << 123 << "|" << 123 << endl; // | 123|123
// setw() is non-sticky. "|" and 123 displayed with default width
cout << "|" << setw(5) << -123 << "|" << endl; // | -123|123
// minus sign is included in field width
cout << "|" << setw(5) << 1234567 << "|" << endl; // |1234567|
// no truncation of data
Example: Alignment
Tulsiramji Gaikwad-Patil College of Engineering and
Technology
Wardha Road, Nagpur-441 108
NAAC Accredited Grade A+
Approved by AICTE, New Delhi, Govt. of Maharashtra & Affiliated to RTM Nagpur
University, Nagpur
cout << showpoint << 123. << "," << 123.4 << endl; // 123.000,123.400
cout << noshowpoint << 123. << endl; // 123
// fixed-point formatting
cout << fixed;
cout << "|" << 1234567.89 << "|" << endl; // |1234567.890000|
// default precision is 6, i.e., 6 digits after the decimal point
// scientific formatting
cout << scientific;
cout << "|" << 1234567.89 << "|" << endl; // |1.234568e+006|
// default precision is 6, i.e., 6 digits after the decimal point
// Test precision
cout << fixed << setprecision(2); // sticky
cout << "|" << 123.456789 << "|" << endl; // |123.46|
cout << "|" << 123. << "|" << endl; // |123.00|
cout << noboolalpha << false << "," << true << endl; // 0,1
Other manipulators
● skipws|noskipws: skip leading white spaces for certain input operations.
● unitbuf|nounibuf: flush output after each insertion operation.
Notes
● You need to include the <iomanip> header for setw(), setprecision(), setfill(),
and setbase().
● You can use ios_base's (in <iostream> header) member functions setf() and unsetf() to set the
individual formatting flags. However, they are not as user-friendly as using manipulators as
discussed above. Furthermore, they cannot be used with cout << operator.
1.11 The C++ string class Input/Output
[TODO]
Tulsiramji Gaikwad-Patil College of Engineering and
Technology
Wardha Road, Nagpur-441 108
NAAC Accredited Grade A+
Approved by AICTE, New Delhi, Govt. of Maharashtra & Affiliated to RTM Nagpur
University, Nagpur
By default, opening an output file creates a new file if the filename does not exist; or truncates it (clear its
content) and starts writing as an empty file.
open(), close() and is_open()
void open (const char* filename,
Tulsiramji Gaikwad-Patil College of Engineering and
Technology
Wardha Road, Nagpur-441 108
NAAC Accredited Grade A+
Approved by AICTE, New Delhi, Govt. of Maharashtra & Affiliated to RTM Nagpur
University, Nagpur
void close (); // Closes the file, flush the buffer and disconnect from stream
object
Program Notes:
● Most of the <fstream> functions (such as constructors, open()) supports filename in C-string only.
You may need to extract the C-string from string object via the c_str() member function.
● You could use is_open() to check if the file is opened successfully.
● The get(char &) function returns a null pointer (converted to false) when it reaches end-of-file.
2.4 Binary file, read() and write()
We need to use read() and write() member functions for binary file (file mode of ios::binary),
which read/write raw bytes without interpreting the bytes.
1/* Testing Binary File IO (TestBinaryFileIO.cpp) */
2#include <iostream>
3#include <fstream>
4#include <cstdlib>
5#include <string>
6using namespace std;
7
8int main() {
9 string filename = "test.bin";
10
11 // Write to File
12 ofstream fout(filename.c_str(), ios::out | ios::binary);
13 if (!fout.is_open()) {
14 cerr << "error: open file for output failed!" << endl;
15 abort();
16 }
17 int i = 1234;
18 double d = 12.34;
19 fout.write((char *)&i, sizeof(int));
20 fout.write((char *)&d, sizeof(double));
21 fout.close();
22
23 // Read from file
24 ifstream fin(filename.c_str(), ios::in | ios::binary);
25 if (!fin.is_open()) {
26 cerr << "error: open file for input failed!" << endl;
27 abort();
28 }
29 int i_in;
30 double d_in;
Tulsiramji Gaikwad-Patil College of Engineering and
Technology
Wardha Road, Nagpur-441 108
NAAC Accredited Grade A+
Approved by AICTE, New Delhi, Govt. of Maharashtra & Affiliated to RTM Nagpur
University, Nagpur
Random access file is typically process as binary file, in both input and output modes.
[TODO] Example
3. String Streams
C++ provides a <sstream> header, which uses the same public interface to support IO between a
program and string object (buffer).
The string streams is based on ostringstream (subclass of ostream), istringstream (subclass
of istream) and bi-directional stringstream (subclass of iostream).
typedef basic_istringstream<char> istringstream;
typedef basic_ostringstream<char> ostringstream;
Stream input can be used to validate input data; stream output can be used to format the output.
Tulsiramji Gaikwad-Patil College of Engineering and
Technology
Wardha Road, Nagpur-441 108
NAAC Accredited Grade A+
Approved by AICTE, New Delhi, Govt. of Maharashtra & Affiliated to RTM Nagpur
University, Nagpur
ostringstream
explicit ostringstream (ios::openmode mode = ios::out); // default with empty string
explicit ostringstream (const string & buf,
ios::openmode mode = ios::out); // with initial str
For example,
// Get contents
cout << sout.str() << endl;
The ostringstream is responsible for dynamic memory allocation and management.
istringstream
explicit istringstream (ios::openmode mode = ios::in); // default with empty string
explicit istringstream (const string & buf,
ios::openmode mode = ios::in); // with initial string
For example,