0% found this document useful (0 votes)
12 views23 pages

bplck-205d-module-4

Module 4 of the Introduction to C++ course covers input and output streams, detailing how C++ handles data flow through streams defined in the <iostream> library. It explains the types of streams (input, output, error) and introduces various functions for unformatted and formatted I/O operations, including predefined streams like cin and cout, as well as file handling using fstream. Additionally, it discusses manipulators and methods for formatting output, such as width, precision, and fill, along with classes for file stream operations.

Uploaded by

nishankmn03
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
12 views23 pages

bplck-205d-module-4

Module 4 of the Introduction to C++ course covers input and output streams, detailing how C++ handles data flow through streams defined in the <iostream> library. It explains the types of streams (input, output, error) and introduces various functions for unformatted and formatted I/O operations, including predefined streams like cin and cout, as well as file handling using fstream. Additionally, it discusses manipulators and methods for formatting output, such as width, precision, and fill, along with classes for file stream operations.

Uploaded by

nishankmn03
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 23

lOMoARcPSD|40175572

Bplck 205D Module 4

Introduction to C++ (Visvesvaraya Technological University)

Scan to open on Studocu

Studocu is not sponsored or endorsed by any college or university


Downloaded by UMESH D R ([email protected])
lOMoARcPSD|40175572

MODULE-4
INPUT/OUTPUT STREAMS (C++ STREAMS)
C++ comes with libraries that provide us with many ways for performing input and output. In C++
input and output are performed in the form of a sequence of bytes or more commonly known
as streams.
Streams are defined in the streams library header file <iostream> and implemented in the iostream
library.
• Input Stream: If the direction of flow of bytes is from the device (for example, Keyboard) to
the main memory then this process is called input.
• Output Stream: If the direction of flow of bytes is opposite, i.e. from main memory to
device( display screen ) then this process is called output
Input stream

Input device

Program

Output device

Output stream
Fig. Data streams
➢ Stream can be act as a source from which the input data can be obtained or as a destination to
which the output data can be sent.
➢ The source stream that provides data to the program is called the input stream.
➢ The destination stream that receives output from the program is called the output stream.
➢ A program extracts bytes from an input stream
➢ A program inserts bytes into an output stream.
➢ The data in the input stream can come from the keyboard or any other storage device.
➢ The data in the output stream can go to the screen or any other storage device.
➢ A stream acts as an interface between the program and the input/output device.

Predefined or built-in Streams in c++:


Predefined streams are those streams that are embedded in the system by default. These streams
get activated, when the program execution starts.
The multiple predefined streams that are available in C++ are,
• 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

Downloaded by UMESH D R ([email protected])


lOMoARcPSD|40175572

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.

• 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(<<).

• 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.
The main difference between cerr and cout comes when you would like to redirect output
using “cout” that gets redirected to file if you use “cerr” the error doesn’t get stored in
file.(This is what un-buffered means ..It cant store the message)

• (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.

Downloaded by UMESH D R ([email protected])


lOMoARcPSD|40175572

Unformatted input/output operations In C++


Unformatted console input/output functions are used to read a single input from the user at
console and it also allows us to display the value in the output to the user at the console.

put() and get() functions:


The class istream and ostream have predefined functions get() and put(), to handle single
character input and output operations.
get():-
The function get() can be used in two ways, such as get(char*) and get(void) to fetch characters
including blank spaces, newline characters, and tab. The function get(char*) assigns the value to a
variable and get(void) to return the value of the character.

Downloaded by UMESH D R ([email protected])


lOMoARcPSD|40175572

Example:
1.char data;
// get() return the character value and assign to data variable
data = cin.get();
2. char c;
// directly assign value to c
cin.get(c);

put():-
The put() function is a member of the ostream class, and used to output a line of text, character by
character. For example,
cout.put(‘x’);
in the above statement displays the character x and
cout.put(ch);
Here displays the value of variable ch.
The variable ch must contain a character value. We can also use a number as an argument to the
function put(). For example,
cout.put(68);
displays the character D. This statement will convert the int value 68 to a char value and display
the character whose ASCII value is 68. The following segment of a program reads a line of the text
from keyboard and also displays it on the screen.
char c;
cin.get(c); // in this statement read a character
while(c ! = ‘\n’)
{
cout.put(c); // displays the character on screen
cin.get(c);
}

Example program character I/O with get() and put()

#include <iostream>
using namespace std;
int main()
{
int count = 0;
char c;
cout << "INPUT TEXT\n";
cin.get(c);
while (c != '\n')
{
cout.put(c);
count++;
cin.get(c);
}
cout << "\nNumber of characters = " << count << "\n";

Downloaded by UMESH D R ([email protected])


lOMoARcPSD|40175572

return 0;
}
PROGRAM OUTPUT
Input
Object Oriented Programming
output
Object Oriented Programming
Number of characters = 27

getline() and write() functions:


In C++, the function getline() and write() provide a more efficient way to handle line-
oriented inputs and outputs.
getline() function reads the complete line of text that ends with the new line character. This
function can be invoked using the cin object.
Syntax:
cin.getline(variable_to_store_line, size);
The reading is terminated by the ‘\n’ (newline) character. The new character is read by the
function, but it does not display it, instead, it is replaced with a NULL character. After reading a
particular string the cin automatically adds the newline character at end of the string.
The write() function displays the entire line in one go and its syntax is similar to the getline()
function only that here cout object is used to invoke it.
Syntax:
cout.write(variable_to_store_line, size);
The key point to remember is that the write() function does not stop displaying the string
automatically when a NULL character occurs. If the size is greater than the length of the line then,
the write() function displays beyond the bound of the line.
#include <iostream>
#include <string>
using namespace std;

int main()
{
char line[100];
cin.getline(line, 10);
cout.write(line, 5);
cout << endl;
cout.write(line, 20);
cout << endl;
return 0;
}

Downloaded by UMESH D R ([email protected])


lOMoARcPSD|40175572

Formatted I/O functions in C++


The iomanip.h and iostream.h header files are used to perform the formatted IO operations in
C++.
The C++ programming language provides the several built-in functions to display the output in
formatted form. These built-in functions are available in the header file iomanip.h and ios class of
header file iostream.h.

In C++, there are two ways to perform the formatted IO operations.

• Using the member functions of ios class.


• Using the special functions called manipulators defined in iomanip.h

Formatted IO using ios class memebers

The ios class contains several member functions that are used to perform formmate IO operations.

width(): The width method is used to set the required field width. The output will be displayed in the
given width. The default width of your output will be just enough space to print the number,
character, or string in the output buffer. You can change this by using width(). Because width() is a
member function, it must be invoked with a cout object. It only changes the width of the very next
output field and then immediately reverts to the default.

cout.width(w); where w is the field width

example:-

cout.width(5);
cout<<”123”;
output:-
1 2 3

precision(): The precision method is used to set the number of the decimal point to a float value
By default, the floating numbers are printed with six digits after the decimal point.
To specify the number of digits after the decimal point using the precision()
cout.precision();
Where d is the number of digits to the right of the decimal point.
fill(): The fill method is used to set a character to fill in the blank space of a field.
By default,the unused positions of the field are filled with white spaces.
The use of fill() to fill the unused positions by any desired character.
cout.fill(ch);
Where ch represents the character which is used for filling the unused positions.
Example:
OUTPUT:

* * 1 2 3

Downloaded by UMESH D R ([email protected])


lOMoARcPSD|40175572

cout.fill(‘*’);
cout.width(5);
cout<<123;

setf(): The setf method is used to set various flags for formatting output.
The function setf() sets the iostream format flags of the current stream to flags. The
optional needed argument specifies that only the flags that are in both flags and needed should be
set. The return value is the previous configuration of iostream format flags.
cout.setf(arg1,arg2);
where arg1 is one of the formatting flags defined in the class ios. The formatting flag specifies the
format action required for the output.
arg2 represents as bit field specifies the group to which the formatting flag belongs.
Where set bits is one of the flags defined in the class ios. It specifies the format action required for
the output, and field specifies the group to which the formatting flag belongs. Both the forms
return the previous settings. The flags, bit-fields when set with setf() and their actions is shown in
table.

The following table shows that some of flag value without bit fields for the setf function.

Downloaded by UMESH D R ([email protected])


lOMoARcPSD|40175572

unsetf(): The unsetf method is used To remove the flag setting.


cout.unsetf(arg);

example:

#include <iostream>
#include <fstream>
using namespace std;
int main()
{
cout << "Example for formatted IO" << endl;
cout << "Default: " << endl;
cout << 123 << endl;

cout << "width(5): " << endl;


cout.width(5);
cout << 123 << endl;

cout << "width(5) and fill('*'): " << endl;


cout.width(5);
cout.fill('*');
cout << 123 << endl;

cout.precision(5);
cout << "precision(5) ---> " << 123.4567890 << endl;
cout << "precision(5) ---> " << 9.876543210 << endl;

cout << "setf(showpos): " << endl;


cout.setf(ios::showpos);
cout << 123 << endl;

cout << "unsetf(showpos): " << endl;


cout.unsetf(ios::showpos);
cout << 123 << endl;

return 0;
}

Downloaded by UMESH D R ([email protected])


lOMoARcPSD|40175572

Formatted IO using manipulators


The iomanip.h header file contains several special functions that are used to perform formmated
IO operations.
The following table provides the details of the special manipulator functions used to perform
formatted IO in C++.

Function Description
setw(int) Used to set the width in number of characters for the immediate
output data.
setfill(char) Used to fill the blank spaces in output with given character.

setprecision(int) Used to set the number of digits of precision.

setbase(int) Used to set the number base.

setiosflags(format flags) Used to set the format flag.

resetiosflags(format Used to clear the format flag.


flags)

The iomanip.h also contains the following format flags using in formatted IO in C++.
Flag Description
endl Used to move the cursor position to a newline.
ends Used to print a blank space (null character).
dec Used to set the decimal flag.
oct Used to set the octal flag.
hex Used to set the hexadecimal flag.
left Used to set the left alignment flag.

Downloaded by UMESH D R ([email protected])


lOMoARcPSD|40175572

Flag Description
right Used to set the right alignment flag.
showbase Used to set the showbase flag.
noshowbase Used to set the noshowbase flag.
showpos Used to set the showpos flag.
noshowpos Used to set the noshowpos flag.
showpoit Used to set the showpoit flag.
noshowpoint Used to set the noshowpoint flag.

File streams:-
• A file is a collection of related data stored in a particular area on the disk.
• Programs can be designed to perform the read and write operations on these files.
• In general a file is a sequence of bits, bytes, lines or records whose meaning is defined by its
user.
• In C++, file input/output facilities are implemented through a header file fstream.h.

To read and write from a file we are using the standard C++ library called fstream. Let us see the
data types define in fstream library is:

Data Description
Type

fstream It is used to create files, write information to files, and read information
from files.

ifstream It is used to read information from files.

ofstream It is used to create files and write information to the files.

Classes for file stream operation:


• The I / O system of C++ contains a set of classes that define the file handling methods.
• These include ifstream, ofstream and fstream.
• These classes are derived from fstream base and from the corresponding iostream.h.
• These classes, designed to manage the disk files, are declared in fstream.h and therefore we
must include this file in any program that uses files.

Downloaded by UMESH D R ([email protected])


lOMoARcPSD|40175572

1. ios:-

• ios stands for input output stream.


• This class is the base class for other classes in this class hierarchy.
• This class contains the necessary facilities that are used by all the other derived classes for
input and output operations.
2. istream:-

• istream stands for input stream.


• This class is derived from the class ‘ios’.
• This class handle input stream.
• The extraction operator(>>) is overloaded in this class to handle input streams from files to
the program execution.
• This class declares input functions such as get(), getline() and read().

3. ostream:-

• ostream stands for output stream.


• This class is derived from the class ‘ios’.
• This class handle output stream.
• The insertion operator(<<) is overloaded in this class to handle output streams to files from
the program execution.
• This class declares output functions such as put() and write().
4. streambuf:-

• This class contains a pointer which points to the buffer which is used to manage the input
and output streams.

Downloaded by UMESH D R ([email protected])


lOMoARcPSD|40175572

5. fstreambase:-

• This class provides operations common to the file streams. Serves as a base for fstream,
ifstream and ofstream class.
• This class contains open() and close() function.
6. ifstream:-

• This class provides input operations.


• It contains open() function with default input mode.
• Inherits the functions get(), getline(), read(), seekg() and tellg() functions from the istream.
7. ofstream:-

• This class provides output operations.


• It contains open() function with default output mode.
• Inherits the functions put(), write(), seekp() and tellp() functions from the ostream.
8. fstream:-

• This class provides support for simultaneous input and output operations.
• Inherits all the functions from istream and ostream classes through iostream.
9. filebuf:-

• Its purpose is to set the file buffers to read and write.


• We can also use file buffer member function to determine the length of the file.

Types of data Files:

Generally there are two types of files in C++:


Text Files:
• A text file is a file that stores the information in ASCII characters.
• Each line of text is terminated by a special character, known as End of Line (EOL) or
delimiter.
Binary Files:
• A binary file is a file that contains information in the same format as it is held in memory.
• In binary files, no delimiters are used for a line and no translations occur here.

Text File vs Binary File


The following are some of the differences between text files and binary files.

S.
No. Text file Binary File

Binary files cannot easily be transferred from


The text files can easily be transferred
one computer system to another due to
1. from one computer system to another.
variations in the internal variations in the

Downloaded by UMESH D R ([email protected])


lOMoARcPSD|40175572

S.
No. Text file Binary File

internal representation which varies from


computer to computer.

It stores data using ASCII format i.e. It stores data in binary format i.e. with the
2. human-readable graphic characters. help of 0 and 1.

These files are easily readable and


modifiable because the content written in
text files is human readable. These files are not easily readable and
Content written in binary files is not modifiable because the content written in
human-readable and looks like encrypted binary files is not human-readable and it is
3. content. encrypted content.

4. These files create portability problems. These files are easily portable.

Text files save the data by converting each


digit in data into ASCII format which will
take up much of the space as compared to These save memory because the data of any
the required one. type will get stored in memory as per its
memory size.
For example, the number 546378 is an
integer that should occupy 4 bytes in the For example, any integer number irrespective
disk but it will occupy 6 bytes, 1 byte for of individual digits in the number will be
5. each digit in the number. stored by consuming 4 bytes.

The ios:: binary mode has to be used with


6. Any file is by default text file. binary files while opening them.

Error in a textual file can be easily Error in a binary file corrupts the file and is
7. recognized and eliminated. not easily detected.

In a text file, a new line character is first In binary file, no such conversion from
8.
converted to a carriage return-line feed newline to carriage return-line feed

Downloaded by UMESH D R ([email protected])


lOMoARcPSD|40175572

S.
No. Text file Binary File

combination and then written to the disk. combination is done.


Vice versa happens when a line is read
from the text file.

In a text file, a special character with


ASCII code 26 is inserted at the end of the
file. This character signals the EOF to the There is no such special character in the
9. program when encountered. binary file to signal EOF.

Text files are used to store data more user Binary files are used to store data more
10. friendly. compactly.

Mostly .txt and .rtf are used as extensions


11. to text files. Can have any application defined extension.

Opening and Closing of Files:


• A file must first be opened before data can be read from it or written to it.
• In C++ there are two ways to open a file with the file stream object.
➢ Opening file using constructor.
➢ Opening file using open ( ) member function.
• 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.

Opening files using Constructors:


• In order to access a file, it has to be opened either in read, write or append mode.
• In all the three file stream classes, a file can be opened by passing a filename as the first
parameter in the constructor itself.
This method involves some steps:-
✓ Create a filestream object to manage the stream using the appropriate class.i.e,the class
ofstream is used to create output stream. The class ifstream is used to create input stream.
✓ Initialize the file object with the desired filename.
• The syntax for opening a file using constructor is

Downloaded by UMESH D R ([email protected])


lOMoARcPSD|40175572

streamclass_name file_objectname (“filename”)

• The syntax of opening a file for output purpose only using an object ofstream class and the
constructor is as follows:
ofstream ofstream_object(“file name”);
Example: ofstream fout (“results.dat”);
Where fout is declared as an object of ofstream type and it is opened result.dat file for output
purpose.
• The syntax of opening a file for input purpose only using an object ifstream class and the
constructor is as follows:
ifstream ifstream_object(“file name”);
Example: ifstream fin (“results.dat”);
Where fin is declared as an object of ifstream type and it is opened result.dat file for input
purpose.

Opening files using open( ):


• open( ) can be used to open multiple files that use the same stream object.
• The syntax for opening a file using open ( ) member function is as follows:
file_stream_class stream_object; stream_object.open (“file_name”);
• The syntax of opening a file for output purpose only using an object ofstream class and open(
) member function is as follows:
oftream_object.open(“file name”);
Example: ofstream outfile;
outfile.open (“data”);
outfile.open (“text.dat”);
• The syntax of opening a file for input purpose only using an object ifstream class and open( )
member function is as follows:
iftream_object.open(“file name”);
Example: ifstream ifile;
ifile.open (“data”);
• To open a file for both input and output, we declare objects of fstream class. We know that
the class fstream is derived from both ifstream and ofstream,
• The syntax for opening a file an object of type fstream class and the constructor is as
follows:
fstream fstream-object(“file name’, mode);
• The syntax for opening a file an object of type fstream class and the open( ) member function
is as follows:
fstream-object.open(“file name’, mode);

Downloaded by UMESH D R ([email protected])


lOMoARcPSD|40175572

File Modes:
While using constructors or open( ), the files were created or opened in the default mode.
There was only one argument passed, i.e. the filename. C++ provides a mechanism of opening a file
in different modes in which case the second parameter must be explicitly passed.
Syntax:
stream_object.open(“filename”, mode);
Example: fout.open(“data”, ios::app) // This opens the file data in the append mode.
The lists of file modes are:

Example:
fstreamfout (“text”, ios::out); // open text in output mode
fstream fin(“text”, ios::in); // open text in input mode
fout.open(“data”, ios::app) // This opens the file data in the append mode
fout.open(“data”, ios::app | ios::nocreate) // This opens the file in the append mode but fails
to open if it does not exist

• The mode can be combine two or more parameter using the bitwise OR operator( | )
Example: fout.open(“data”,ios::app|ios::nocreate);

Closing File:
• Opening a file eshtablishes the linkage between a stream object and an operating system file.
• After the intended operations are done with the file then we removes the linage between the
file and the stream object
• The member function close( ) on its execution removes the linkage between the file and the
stream object.

Downloaded by UMESH D R ([email protected])


lOMoARcPSD|40175572

• After close the file; the file should be safely saved on the secondary storage in the memory.
Syntax: stream_object.close( );
Example: ofstream.close( );
ifstream.close( );

Input and output operation in text file:


• The data in text files are organized into lines with new line character as terminator.
• Text file need following types of character input and output operations:
✓ put( ) function
✓ get( ) function
put ( ):

• The put( ) member function belongs to the class ofstream and writes single character to the
associated stream.
Syntax: ofstream_object.put(ch); // where ch is the character variable.
Example: char ch=’A’;
ofstream fout(“text.txt”);
fout.put (ch);

• fout is the object of ofstream. Text is the name of the file. Value at ch is written to text.

get( ):

• The get( ) member function belong to the class ifstream and reads a single character from the
associated stream.
Syntax: ifstream_object.get (ch); // where ch is the character variable.
Example: char ch;
ifstream fin(“text.txt”);
fin.get (ch);
• fin is the object of ifstream. Text is the name of the file. Reads a character into the variable
ch.
getline( ):

• It is used to read a whole line of text. It belongs to the class ifstream.


Syntax: fin.getline(buffer, SIZE)
• It reads SIZE characters from the file represented by the object fin or till the new line
character is encountered, whichever comes first into the buffer.
Example: char book[SIZE];
ifstream fin;
fin.getline (book, SIZE);

Downloaded by UMESH D R ([email protected])


lOMoARcPSD|40175572

Input and output operation in binary files:


• Binary files are very much use when we have to deal with database consisting of records.
The binary format is more accurate for storing the numbers as they are stored in the exact
internal representation.
• There is no conversion while saving the data and hence it is faster.
• Functions used to handle data in binary form are:
▪ write ( ) member function.
▪ read ( ) member function
write ( ):

• The write ( ) member function belongs to the class ofstream and which is used to write
binary data to a file.
Syntax: ofstream_object.write((char *) & variable, sizeof(variable));

• These functions take 2 arguments. The first is the address of the variable and second the size
of the variable in bytes. The address of the variable must be type casted to pointer to
character.
Example: student s;
ofstream fout(“std.dat”, ios::binary);
fout.write((char *) &s, sizeof(s));

read ( ):

• The read ( ) member function belongs to the class ifstream and which is used to read binary
data from a file.
Syntax: ifstream_object.read((char *) & variable, sizeof(variable));
These functions take 2 arguments. The first is the address of the variable and second
the size of the variable in bytes. The address of the variable must be type casted to pointer to
character.
Example: student s;
ifstream fin(“std.dat”, ios::binary);
fin.write((char *) &s, sizeof(s));

Detecting End of file:


• Detecting end of file is necessary for preventing any further attempt to read data from the file.
• eof( ) is a member function of ios class. Which helps to detect the end of file.
• Once the end of the file is detected with the help of eof() then we can stop reading further.

Downloaded by UMESH D R ([email protected])


lOMoARcPSD|40175572

• It returns a non-zero (true) value if the end of file condition is encountered while reading;
otherwise returns a zero (false).
• Example:
ifstream fin;
if(fin.eof( ))
{
statements;
}
This is used to execute set statements on reaching the end of the file by the object fin.

File pointers and their manipulation:


• In C++, the file I/O operations are associated with the two file pointers:
▪ Input pointer (get pointer)
▪ Output pointer (put pointer)
• We use these pointers to move through files while reading or writing.
• Each time an input or output operation takes place, appropriate pointer is automatically
advanced.
❖ ifstream, like istream, has a pointer known as get pointer that points to the element to
be read in the next input operation.
❖ ofstream, like ostream, has a pointer known as put pointer that points to the location
where the next element has to be written.
• There are three modes under which we can open a file:
▪ Read only mode
▪ Write only mode
▪ Append mode

• When we open a file in read only mode, the input pointer is automatically set to the first byte
as 0 at the beginning so that we read the file from the beginning.
• When we open a file in write only mode, the existing contents are deleted and output pointer
is set at the beginning

Downloaded by UMESH D R ([email protected])


lOMoARcPSD|40175572

• If we want to open an existing file to add more data, the file is opened in append mode. This
moves the file pointer to the end of the file, so that we write new data from that location.

Functions for manipulation of file pointers:


• To move file pointers to any desired position inside a file, file stream classes support the
following functions.
▪ seekg() - Moves get file pointer to a specific location
▪ seekp() - Moves put file pointer to a specific location
▪ tellg() - Returns the current position of the get pointer
▪ tellp() - Returns the current position of the put pointer
• The seekp() and tellp() are member functions of ofstream
• The seekg() and tellg() are member functions of ifstream.
• All four functions are available in the class fstream.
seekg( ):

• Move the get pointer to a specified location from the beginning of a file.
There are two types:
▪ seekg(long);
▪ seekg(offset, seekdir);
• The seekg(long) moves the get pointer to a specified location from the beginning of a file.
Example: inf.seekg(20);

• The seekg(offset, seekdir) has two arguments: offset and seekdir.


• The offset indicates the number of bytes the get pointer is to be moved from seekdir position.
• seekdir takes one of the following three seek direction constants.
Constants Meaning
ios::beg These are used from the beginning of the file
ios::end These are used from the end of the file

ios::cur These are used from the current position in


the file.

Syntax: stream_objectname.seekg(offset, origin_value);


Example : Some of the pointer offset calls and their actions are shown in the following table

seekg( ) function option Action performed


object.seekg(0, ios::beg) Take get pointer to the beginning of the file
object.seekg(0, ios::end) Go to end of the file
object.seekg(0, ios::cur) Stay get pointer at the current position.
object.seekg(m, ios::beg) Move forward by (m+1) bytes in the file

Downloaded by UMESH D R ([email protected])


lOMoARcPSD|40175572

object.seekg(-m, ios::end) Go backward by m bytes from the file end.

seekp ( ):

• Move the put pointer to a specified location from the beginning of a file.
There are two types:
▪ seekp(long);
▪ seekp(offset, seekdir);
• The seekp(long) moves the put pointer to a specified location from the beginning of a file.
Example: inf.seekp(20);

• The seekp(offset, seekdir) has two arguments: offset and seekdir.


• The offset indicates the number of bytes the put pointer is to be moved from seekdir position.
syntax: stream_objectname.seekp(offset, origin_value);

seekp( ) function option Action performed


object.seekg(0, ios::beg) Go to beginning of the file for writing
object.seekg(0, ios::end) Go to end of the file for writing
object.seekg(0, ios::cur) Stay at the current position for writing.
object.seekg(m, ios::beg) Move forward by m bytes from the beginning for writing
object.seekg(-m, ios::end) Go backward by m bytes from the end for writing

tellg ( ) and tellp( ):

• tellg( ) returns the current position of the get pointer.


Syntax: position = ifstream_object.tellg( );
Example: int position;
position= fin.tellg();

• tellp( ) returns the current position of the put pointer.


Syntax: position = ifstream_object.tellp( );
Example: int position;
position= fin.tellp();
Error Handling during File Operations
It's quite common that errors may occur during file operations. There may have different reasons for
arising errors while working with files. The following are the common problems that lead to errors
during file operations.

Downloaded by UMESH D R ([email protected])


lOMoARcPSD|40175572

• When trying to open a file for reading might not exist.


• When trying to read from a file beyond its total number of characters.
• When trying to perform a read operation from a file that has opened in write mode.
• When trying to perform a write operation on a file that has opened in reading mode.
• When trying to operate on a file that has not been open.
During the file operations in C++, the status of the current file stream stores in an integer flag
defined in ios class. The following are the file stream flag states with meaning.

Error Handling During the File Operations in C++


The C++ programming language provides several built-in functions to handle errors during file
operations. The file error handling
The following are the built-in functions to handle file errors.

Function Return Value

bad() It returns a non-zero (true) value if an invalid operation is attempted or an unrecoverable


error has occurred. Returns zero if it may be possible to recover from any other error
reported and continue operations.

fail( ) It returns a non-zero (true) value when an input or output operation has failed.

good() It returns a non-zero (true) value when no error has occurred; otherwise returns zero
(false).

eof( ) It returns a non-zero (true) value when end-of-file is encountered while reading; otherwise
returns zero (false).

clear()-this function used to reset the error statethen we attempt further operation.

Downloaded by UMESH D R ([email protected])

You might also like