0% found this document useful (0 votes)
7 views35 pages

C++ File and Stream Handling Guide

The document covers the concepts of files and streams in C++, including data hierarchy, stream classes, and file I/O operations. It discusses various functions for manipulating file pointers, command-line arguments, and formatted/unformatted input/output functions. Additionally, it includes sample questions from past exam papers related to these topics, emphasizing practical programming examples and error handling.

Uploaded by

Kartik Ingle
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)
7 views35 pages

C++ File and Stream Handling Guide

The document covers the concepts of files and streams in C++, including data hierarchy, stream classes, and file I/O operations. It discusses various functions for manipulating file pointers, command-line arguments, and formatted/unformatted input/output functions. Additionally, it includes sample questions from past exam papers related to these topics, emphasizing practical programming examples and error handling.

Uploaded by

Kartik Ingle
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

Unit IV Files and Streams (07 Hours)

Data hierarchy, Stream and files, Stream Classes, Stream Errors, Disk File I/O with Streams, File
Pointers, and Error Handling in File I/O, File I/O with Member Functions, Overloading the Extraction
and Insertion Operators, memory as a Stream Object, Command-Line Arguments, Printer output.

SPPU May-June 2023 ESE Question Paper


Q.3) a) what are various functions which are used to manipulate file pointers? Explain using
example[7]
b) Explain command line arguments in C++? Write program to explain the same. [7]
c) What are different file opening mode? [4]
OR
Q4)a)Explain formatted and unformatted i/p and o/p functions used in C++ with example. [7]
b) What are stream classes &their use? Provide the hierarchy of stream classes in C++. [7]
c) Explain the use of command line arguments. If we want to pass command line arguments what will
be prototype of main function and explain its arguments along with example. [4]

SPPU Nov-Dec 2022 ESE Question Paper


Q3) a) what are various functions used to manipulate file pointers? Explain using example. [7]
b) What are command line arguments in C++? Write a program to explain the same. [7]
c) What are fstream, ifstream and ofstream? Illustrate with help of example. [4]
OR
Q4) a) Write a program to create file, read and write record into it. Every record contains employee
name, id and salary. Store and retrieve at-least 3 data. [7]
b) What do you mean by file handling? Explain following functions. i) open() ii) get() iii) getline() [7]
c) Write a program to create files using constructor function. [4]

SPPU Nov-Dec 2023 ESE Question Paper


Q3) a) Explain the use of command line arguments. If we want to pass command line arguments what
will be prototype of main function and explain its arguments along with example. [5]
b) Explain the following file handling functions (solve any three).
i) seekg ( ) ii) tellg ( ) iii) seekp ( ) iv) tellp ( ) [6]
c) Write a program Using the C++ file input and output class with open(), get(), put(),close() methods
for opening, reading from and writing to a file. Use append mode while opening the file for writing.[7]
OR
Q4) a) List and Explain different Mode bits used in open () function, while opening a file.(Any 5). [5]
b) Define a class Person that has three attributes viz name, gender and age. Write a C++ Program that
writes an object to a file and reads an object from a file. [6]
c) Explain what is fstream, ifstream and ofstream with help of example? Provide the hierarchy of
stream classes in C++. [7]

Unit IV
Files and Streams
Data hierarchy:-
Ultimately, all data items that computers process are reduced to combinations of Os and ls.
This occurs because it is simple and economical to build electronic devices that can assume two stable
states, one represents 0 and the other represents 1.
It is remarkable that the impressive functions performed by computers involve only the most
fundamental manipulations of 0s and ls.
The smallest data item that computers support is called a bit (short for "binary digit" a digit that
can assume one of two values). Each data item, or bit, can assume either the value 0 or the value 1.
Computer circuitry performs various simple bit manipulations, such as examining the value of
a bit, setting the value of a bit and reversing a bit (from 1 to 0 or from 0 to 1).
Data items processed by computers form a data hierarchy as shown in Fig. 5.1.1, in which data
items become larger and more complex in structure as we progress from bits to characters to fields to
larger data aggregates:
Stream and files: -
A stream is sequences of bytes. It acts as source from which the input data can be obtained or
as a destination to which data input can be sent.
The source stream that provides data to the program is called input the stream and the
destination stream that receives output from the program is called as output stream.
In short, a program takes bytes from input stream and puts bytes into an output stream.
The data in the input stream can come from a device like a keyboard, a disk drive, or a network
connection etc. to main memory, this is called input stream.

Similarly, the data in the output stream from main memory to a device like a display
screen, a printer, a disk drive, or a network connection, etc., this is called output stream.

The data in the input stream can come from a device like a keyboard, a disk drive, or a
network connection etc. to main memory, this is called input stream.
Similarly, the data in the output stream from main memory to a device like a display
screen, a printer, a disk drive, or a network connection, etc., this is called output stream.

***C++ Stream classes:-


C++ provides several classes to work with stream based I/O, such classes are known as stream
classes and they are arranged in hierarchy shown in following figure.
Class Name Contents
ios (general input/output Contains basic facilities that are used by all other input and output [Link]
stream classes) also contains a pointer to a buffer object (streambuf object).
istream (input stream) Inherits the properties of ios. Declares input functions such as get°. gelling),
read(), Contains overloaded extraction operator >>.
ostream (Output Stream) Inherits the properties of IOS. Declares output function such as put() and
write(). Contains overloaded insertion operator <<.
Iostream (Input/Output Inherits the properties of IOS stream and ostream through multiple
stream) inheritance and thus contains all the input and output functions.
streambuf Provides an interface to physical devices through [Link] acts as a base
forfilebuf class used in files.
Figure:- Stream classes hierarchy
All these classes are declared in iostream.h header file so we have to include this header file in
order to use the stream classes.
As shown in above figure ios is base class for the stream classes from which istream and
ostream classes are derived.
The class ios is declare as the virtual base class so that it‟s member are inherited by the iostream.
The class istream provides the basic support for formatted and unformatted I/O operations.
The class istream provides the facilities for formatted and unformatted input while the class ostream
provides the facility for the formatted output.
The iostream provides the facility for handling both input and output stream. Details of classes
are shown below

Unformatted I/O operations:-


[Link] and cout:-
cin and cout are used for input and output respectively using operators >> and << to recognized all the
basic C++ type.
Following is general form for reading data from the keyboard
e.g.
cin>>variable1>>variable2>>----------->>variable N;
The general form for displaying data on the screen
e.g
cout<<“Message to display”; OR
cout<<variable1<<variable2<<-----------<<variable N;
2. put() and get() functions:-
The classes istream and ostream define two member function get() and put() respectively to
handle the single character input/output operations.

There are two prototype of get() function


1)get(char *) e.g. [Link](c);
2) get(void) e.g. c = [Link]();

Remember that these functions are members of input/output stream classes, we must
call them using correct object.

1) get(char *) functions:-
#include <iostream>
using namespace std;
int main()
{ char c;
while(c != '\n')
{ [Link](c); //get another character from keyboard
cout<<c; // display character to screen
}
return 0;
}

2. put() functions:-
The function put() , a member ostream classes, can be used to output a line of text , character by
character.
e.g [Link](„X‟);

The above statement display the character „X‟;

e.g. [Link](a);

The above statement display the value of a consider the following sample code , which takes
input and display output.
#include <iostream>
using namespace std;
int main()
{ char c;
[Link](c); //input c
while(c != '\n')
{ [Link](c); // display value of
[Link](c); //get another character from keyboard
}
return 0;
}

3) getline() and write() function:-


For reading and printing a line of text more efficient way is to use getline() and write()
functions.

The getline() function reads a whole line of text that ends with a newline character. This
function can be called by using object of cin as follows
[Link]. getline(line,size);
The write() display the entire line and has the following form [Link]. write(line,size);
The first argument represent name of the strings and second argument represents number of
characters to be displayed.

#include <iostream>
using namespace std;
int main()
{ int size=20; char name[20];
cout<<"\n enter name of student";
[Link](name,size); //input name
cout<<"\n Name of student";
[Link](name,size); //display name
return 0;
}
Formatted console I/O operation:-
C++ supports a wide variety of features which can be used for designing the output.
The features consist of:
1. ios class functions and flags 2. Manipulators 3. User-defined Manipulators

1. ios class functions and flags:-


The ios class consists of a variety of member functions that helps to format the output in many
ways.
The most commonly used ios functions that are used for formatting are
Function Name Task
width() To indicate the essential field size for displaying an output value
precision() To indicatethe digits that are to be displayed after the decimal point of a float value
fill() To denote a character that is used to fill up the unused portion of a field
setf() To denote the format flags that can organize the form of output display
unsetf() To clear the flag that is being specified

1. width()
It is mainly used to describe the width of a field that is required for the output of an item.
Because, it is a member function, it is must to invoke it using an object.
The width( ) function be able to give the field width for only one item, i.e., the item that follow
instantly.
Syntax: [Link](w) // Where w is the field width (number of columns).
#include <iostream>
#include <iomanip>
using namespace std;
int main()
{ char name[50];
cout<<"\n Enter Your Name ";
cin>>name;
cout << "\nIncreasing Width:"<<setw(20) <<name << endl;
return 0;
}
2. precision()
Used to set the number of the decimal point to a float value.
The precision ( ) function tries to preserve the situation in result until it is reorganized.
It is also possible to join the field specification with the precision setting.
Syntax:
[Link](d) ; // Where d is the number of digits to in the number to display
#include <iostream>
#include <iomanip>
using namespace std;
int main()
{ [Link](5);
cout << "precision(5) ---> " << 123.4567890 << endl;
[Link](3);
cout << "precision(3) ---> " << 9.876543210 << endl;
return 0;
}

3. fill()
By default,while printing the values that are having larger field width than required by the
values, the idle positions of the field are filled with white spaces.
This problem can be solved by using the fill( ) function, because it fill up the unused positions
by any preferred character.
Syntax:
[Link](ch);
//Where ch represents the character which is used for filling the unused positions
#include <iostream>
#include <iomanip>
using namespace std;
int main()
{ int x=10;
[Link](5);
[Link]('#');
cout<<x;
return 0;
}
[Link]()
The "set flags" function. Takes as a parameter the flag to be turned "on". Some of the flags that can be
turned on or off are:
flags Description
ios::fixed to specify that floating-point numbers will be printed in fixed notation
ios::scientific to specify that floating-point numbers will be printed in scientific (exponential)
notation.
ios::showpoint specifies that the decimal point will always be printed for floating point types
(even if the value is a whole number, like 4.0
ios::right right-justifies an output item in a field, if a field width is specified
ios::left left-justifies an output item in a field, if a field width is specified.
ios:: showpos display a leading plus sign before positive value

Example: [Link](ios::right);
#include <iostream>
#include <iomanip>
using namespace std;
int main()
{ cout << "setf(showpos): " << endl;
[Link](ios::showpos);
cout << 123 << endl;
[Link](ios::fixed);
cout << 5.8;
[Link](ios::showpoint);
cout << setprecision(3);
cout << 5.8;
return 0;
}
[Link]()
The "unset flags" function. Call this to turn off one of the flags.
Example: [Link](ios::right);

#include <iostream>
#include <iomanip>
using namespace std;
int main()
{ int x=10; float y=10.12345;
cout<<"\n After unseting flags";
[Link](ios::showpos);
cout<<"\n"<<x;
cout<<"\n After unseting flags";
[Link](ios::showpos);
cout<<"\n"<<x;
return 0;
}

Managing output with Manipulators:-


The manipulators are the unique and special stream functions that can be included in the
Input/O utput statements to alter certain characteristics of the input and output.
To use the manipulators, it is must to include the header file <iomanip.h> or <iomanip> in the
program.
The predefined manipulators and their equivalent ios functions are:

Manipulator Equivalent ios function


setw() width()

setprecision() precision()

setfill() fill()

setiosflags() setf()

resetiosflags() unsetf()
1. setw()
The manipulator setw() stands for the set width.
The setw() is mostly used to indicate the minimum number of character positions that a
variable uses on the output field. The default field width is 0.
Syntax:
setw( int w )

2. setfill ( )
The setfill ( ) manipulator function is mainly used to denote a dissimilar character to fill the
unused field width of the value.
Syntax:
setfill( char f)

[Link]()
The setprecision ( ) manipulator function is mainly used to manage the number of digits of
display of an output stream of a floating point value.
The default precision value is 6.
Syntax:
setprecision (int p);

#include <iostream>
#include <iomanip>
using namespace std;
int main()
{ int x=10; float y=10.12345;
cout<<setw(20);
cout<<setfill('#')<<x;
cout<<"\n using setprices=="<<setprecision(4)<<y;
cout<<"\n After seting flags";
cout<<setiosflags(ios::showpos);
cout<<"\n"<<x;
cout<<"\n After reseting flags";
cout<<resetiosflags(ios::showpos);
cout<<"\n"<<x;
return 0;
}
***3. User-defined Manipulators
The programmer can also define his own manipulator according to the requirement of the
program.
Syntax:
ostream & m_name (ostream & o)
{ statement 1;
statement 2;
return 0;
}
The m_name is the name of the manipulator.

#include <iostream>
#include <iomanip>
using namespace std;
ostream & tab (ostream & o)
{ o<<"\t";
return o;
}
int main()
{ cout<<1<<tab<<2<<tab<<3 ;
return 0;
}

Standard error stream (cerr):


cerr is the standard error stream which is used to output the errors. It is an instance of
the ostream class.
As cerr stream is un-buffered so it is used when we need to display the error message
immediately and does not store the error message to display later.
The object of class ostream that represents the standard error stream oriented to narrow
characters(of type char).
It corresponds to the C stream stderr.
The “c” in cerr refers to “character” and „err‟ means “error”, Hence cerr means “character error”.
It is always a good practice to use cerr to display errors.
cerr Syntax
cerr << var_name;
or
cerr << "Some String";
Here,
<< is the insertion operator
var_name is usually a variable, but can also be an array element or elements of containers like
vectors, lists, maps, etc.

#include <iostream>
using namespace std;
// Driver Code
int main()
{ cerr << "Welcome to GfG! :: cerr";
cout << "\nWelcome to GfG! :: cout";
return 0;
}

File
A computer file is a computer resource for recording data discretely in a computer storage
device.
Many real-life problems handle large volumes of data. The data is stored in the devices using
the concept of files. A file is a collection of related data stored in a particular area on the disk.
Programs are designed to perform read and write operations on these files.

Disk File I/O with Streams


Disk File I/O with Streams includes
1. Opening a file operation [Link] a File Operation
3. Writing data to file [Link] data from a file [Link] End of the fie

1. Opening a file operation


A file must be opened before you can read from it or write to it.
Either the ofstream or fstream object may be used to open a file for writing an ifstream object is
used to open a file for reading purposes 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.
Filename is used to initialize the file stream object.
• Create a file stream object to manage the stream.
ofstream is used to create output stream. ifstream is used to create input stream.
• Initialize the file object with the desired filename.
• Eg: ofstream outfile ("[Link]"); // output only
#include<iostream>
#include<fstream>
using namespace std;
int main()
{ ofstream outfile;
cout<<"\n Opening a file ";
[Link] ("[Link]");
cout<<"\n Opening a file is sucessful";
[Link]();
return 0;
}

Opening a file operation using constructor function


#include<iostream>
#include<fstream>
using namespace std;
int main()
{ char name[30]; float cost;
ofstream outf("[Link]");
cout<<"Enter item name:"; cin>>name; outf<<name; //writing to file
cout<<"Enter item cost:"; cin>>cost; outf<<cost; [Link]();
ifstream inf("Item");
inf>>name; inf>>cost; //reading from file
cout<<"\nItem name :" <<name;
cout<<"\nItem cost :"<<cost ; [Link]();
return 0;
}
2. Closing a File Operation
When a C++ program terminates it automatically closes flushes all the streams, release all the
allocated memory and close all the opened files
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.
void close();
#include<iostream>
#include<fstream>
using namespace std;
int main()
{ ofstream outfile;
cout<<"\n Opening a file ";
[Link] ("[Link]");
cout<<"\n Opening a file is sucessful";
[Link]();
return 0;
}

3. Writing data to 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.

e.g ofstream ofs;


ofs<<data;
where ofs is in an object of ofstream i.e output file stream and data contains info to written in
file.
#include<iostream>
#include<fstream>
using namespace std;
int main()
{ int roll;
char name[10];
ofstream ofs("[Link]");
cout<<"\n Enter Roll Number";
cin>>roll;
ofs<<"\n Roll number ==>"<<roll;
cout<<"\n Enter Name of Student";
cin>>name;
ofs<<"\n Name of Student ==>"<<name;
[Link]();
return 0;
}

4. Reading data from a file


You read information from a file into your program using the stream extraction operator (>>)
just as you use that operator to input information from the keyboard.

The only difference is that you use an ifstream or fstream object instead of the cin object.
e.g ifstream inf;
inf>>data;
where inf is in an object of ifstream i.e input file stream and data contained read data from file.
//Before executing this program “[Link]” file contains two value on separate
line [Link] value and [Link] next line any string value like your name
#include<iostream>
#include<fstream>
using namespace std;
int main()
{ int roll;
char name[10];
cout<<"\nReading a data from a file";
ifstream fin("[Link]");
fin>>roll;
cout<<"\n Roll number ==>"<<roll;
fin>>name;
cout<<"\n Name of Student ==>"<<name;
return 0;
}

#include<iostream>
#include<fstream>
using namespace std;
int main()
{ char c, fname[10]; ifstream infile;
[Link]("[Link]");
if([Link]())
{ cout<<"your file did not work";
}
while ([Link]() == 0)
{ [Link](c);
cout << c;
}
return (0);
}
5. Detecting End of the fie
Detection of end of file condition is necessary for preventing any further attempts to read data
from the file.
while(fin)
{
--
---
}
An ifstream object, such as fin ,returns a value of 0 if any error occurs in the file operation
including end of file condition.
Thus, the while loop terminates when fin returns a value of zero on reaching the end of file
condition. Remember, this loop may terminate due to other failure as well.
There is another approach to detect the end of file condition. Note that we have used the
following statement.
e.g. if([Link]() ! = 0)
{ exit(1);
}
eof() is a member function of ios class. It returns a non zero value if the end of file (EOF)
condition is encountered, an a zero otherwise.
Therefore the above statement terminates the program on reaching the end of file.
//Before executing this program “[Link]” only contains one integer value.
#include<iostream>
#include<fstream>
using namespace std;
int main()
{ ifstream fin("[Link]");
while(![Link]())
{ int x;
fin>>x;
cout<<"\n values is==>"<<x;
}
return 0;
}
***File Opening Mode

File mode Meaning

ios::app Append to end of file


ios::ate go to end of file on opening

ios::binary file open in binary mode

ios::in open file for reading only


ios::out open file for writing only

ios::nocreate open fails if the file does not exist

ios::noreplace open fails if the file already exist

ios::trunc delete the contents of the file if it exist

Opening a 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 it already
exists, following will be the syntax:
ofstream outfile;
[Link]("[Link]", ios::out | ios::trunc );
Similar way, you can open a file for reading and writing purpose as follows: fstream file;
[Link]("[Link]", ios::out | ios::in );
#include<iostream>
#include<fstream>
using namespace std;
int main()
{ fstream fp; char ch;
[Link]("[Link]",ios::out); cin>>ch;
while (ch!='.')
{ [Link](ch);
cin>>ch;
}
[Link]();
return 0;
}
***. Write a program to create file, read and write record into it. Every record contains
employee name, id and salary. Store and retrieve atleast 3 data
#include <fstream>
#include <iostream>
using namespace std;
class Employee
{ int id; char name[20]; float salary;
public: void get()
{ cout<<"\nEnter employee name: "; cin>>name;
cout<<"\nEnter employee salary: "; cin>>salary;
cout<<"\nEnter employee id: "; cin>>id;
}
void show()
{ cout<<"\nEmployee Name : "<<name;
cout<<"\nEmployee number : "<<id;
cout<<"\nsalary : "<<salary;
}
};
int main()
{ fstream fin; Employee emp[5]; int i;
[Link]("[Link]",ios::in|ios::out);
cout<<"\n enter employee details";
for(i=0;i<3;i++)
{ emp[i].get();
[Link]((char*) &emp[i],sizeof(emp[i]));
}
[Link](0);
cout<<"\n Employee details";
for(i=0;i<3;i++)
{ [Link]((char*) &emp[i],sizeof(emp[i]));
emp[i].show();
}
return 0;
}
****File Pointers
Each file has two pointers known as file pointers
1. get pointer or input pointer: used for reading the contents of the file.
2. put pointer or output pointer: used for writing to a given file location.
Each time an input or output operation takes place, the appropriate pointer is automatically
advanced.

Default actions are associated with both the pointers.


• When a file is opened in read mode the input pointer is set at the beginning.
• When a file is opened in write mode the existing contents are deleted and output pointer is set
at beginning.

Default actions are associated with both the pointers.


• When a file is opened in read-only mode, the input pointer is automatically set at the beginning
so that file can be read from the start.

• When a file is opened in write-only mode the existing contents are deleted and the output
pointer is set at the beginning.
• This enables us to write the file from start.

• In case an existing file is to be opened in order to add more data, the file is opened in „append‟
mode.
• This moves the pointer to the end of file
***Functions for Manipulations of File pointer
All the actions on the file pointers takes place by default.

The user can control the movement of the pointers as per his need by using file pointers file
stream classes support the following functions
• seekg() Moves get pointer (input)to a specified location.
• seekp() Moves put pointer (output) to a specified location.
• tellg() Give the current position of the get pointer.
• tellp() Give the current position of the put pointer.

#include <iostream>
#include <fstream>
using namespace std;
int main()
{ fstream F; // opening a file in input and output mode
[Link]("[Link]", ios::in | ios::out);
cout <<"\ncurrent location=>"<< [Link]() << endl;
[Link](8, ios::beg);
cout<<"\n seeing 8 bytes/characters=>"<< [Link]() << endl;
char c = [Link]();
cout<<"\n character at current location=>"<< c << endl;
cout <<"\ncurrent location=>"<< [Link]() << endl;
//again, seeking 7 bytes/characters from beginning
[Link](7, ios::beg);
[Link]('Z'); // writting a character 'Z' at current location
[Link](-7, ios::end);
cout << "\nSeeking back 7 bytes/characters from the End:=>" << [Link]() << endl;
c = [Link]();
cout <<"\ncurrent location=>"<< c << endl;
[Link]();
return 0;
}
Specifying the Offset
„Seek‟ functions seekg() and seekp() can also be used with two
arguments as follows:
seekg (offset,refposition); Example:- [Link](10,ios::beg);
seekp (offset,refposition); Example:- [Link](10,ios::beg);
The parameter offset represents the number of bytes the file pointer is to be moved from the
location specified by the parameter refposition.
The refposition takes one of the following three constants defined in the ios class:
• ios::beg Start of file
• ios::cur  Current position of the pointer
• ios::end  End of file
The seekg() function moves the associated file‟s „get‟ pointer while the seekp() function moves
the associated file‟s „put „pointer.
The following table shows some sample pointer offset calls and their [Link] is an
ofstream object.

Pointer offset calls


Seek call Action
[Link](o,ios::beg) Go to start
[Link](o,ios::cur)  Stay at the current position
[Link](o,ios::end)  Go to the end of file
[Link](m,ios::beg) Move to (m+1)th byte in the file
[Link](m,ios::cur)  Go forward by m byte from current position
[Link](-m,ios::cur)  Go backward by m bytes from current position.
[Link](-m,ios::end)  Go backward by m bytes from the end

Error Handling During File Operations


• Following conditions may arise while dealing with files:
▫ A file which we are attempting to open for reading does not exists.
▫ The file name used for a new file may already exists.
▫ 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 invalid file name.
▫ We may attempt to perform an operation when the file is not opened for that purpose.
The ios class supports several member functions that can be used to read the status recorded in a file
stream.

Function Return value and meaning

eof( ) Returns true (non zero value) if end-of-file is encountered while reading otherwise returns false
(zero).

fail( ) Returns true when an input or output operation has failed.

bad ( ) Returns true if an invalid operation is attempted or any unrecoverable error has occurred.
However, if it is false, it may be possible to recover from any other error reported, and
continue operation.

good ( ) Returns true if no error has occurred. When is returns false, no further operations can be
carried out.

These functions can be used at the appropriate places in a program to locate the status of a file stream
and thereby to take the necessary corrective measures. Example:
ifstream infile;
[Link](“ABC”);
while(![Link]())
{ ………….. (process the file)
}
if ([Link]())
{ ……………(terminate the program normally)
}
else
{ if ([Link]())
{ …………….(report fatal error)
}
else
{ [Link](); //clear error state
}
}
The function clear() resets the error state so that further operations can be attempted.
bad Error Handling During File Operations
#include <iostream>
#include <fstream>
using namespace std;
int main()
{ fstream file;
[Link]("[Link]", ios::out);
string data;
file >> data;
if(![Link]())
{ cout << "Operation not success!!!" << endl;
cout << "Status of the badbit: " << [Link]() << endl;
}
else
{ cout << "Data read from file - " << data << endl;
}
return 0;
}
fail Error Handling During File Operations
#include <iostream>
#include <fstream>
using namespace std;
int main()
{ fstream file; string data;
[Link]("[Link]", ios::out);
file >> data;
if([Link]())
{ cout << "Operation not success!!!" << endl;
cout << "Status of the failbit: " << [Link]() << endl;
}
else
{ cout << "Data read from file - " << data << endl;
}
return 0;
}
eof Error Handling During File Operations
#include <iostream>
#include <fstream>
using namespace std;
int main()
{ fstream file;
[Link]("[Link]", ios::in);
string data;
while(![Link]())
{ file >> data;
cout << "data read: " << data << " | eofbit: " << [Link]() << endl;
}
return 0;
}

good Error Handling During File Operations


#include <iostream>
#include <fstream>
using namespace std;
int main()
{ fstream file;
[Link]("[Link]", ios::in);
cout << "goodbit: " << [Link]() << endl;
string data;
cout << endl << "Data read from file:" << endl;
while(![Link]())
{ file >> data;
cout << data << " ";
}
cout << endl;
return 0;
}
File I/O with Member Functions
In Standard C++, you can do I/O to and from disk files very much like the ordinary console I/O
streams cin and tout.
The object cin is a global object in the class istream (input stream), and the global object tout is
a member of the class ()stream (output stream).
File streams come in two flavours :
the class ifstream (input file stream) inherits from istream, and
the class ofstream (output file stream) inherits from ostream.

Thus all of the member functions and operators that you can apply to an istream or ostream
object can also be applied to ifstream and ofstream objects.

However, file streams have some additional member functions and internal information
reflecting how they are connected to files on the disk.
In Standard C++, you can do I/O to and from disk files very much like the ordinary console I/O
streams cin and tout.
The object cin is a global object in the class istream (input stream), and the global object tout is
a member of the class ()stream (output stream).
File streams come in two flavours :
the class ifstream (input file stream) inherits from istream, and
the class ofstream (output file stream) inherits from ostream.

Thus all of the member functions and operators that you can apply to an istream or ostream
object can also be applied to ifstream and ofstream objects.

However, file streams have some additional member functions and internal information
reflecting how they are connected to files on the disk.
Data type Description
ofstream It is used to create files and write on files.

Ifstream It is used to read from files.


Fstream It can perform the function of both ofstream and ifstream which means it can create
files, write on files, and read from files.
File I/O with Member Functions
The syntax for Opening a file is as follows
#include<iomanip>
#include<fstream >
using namespace std;
int main()
{ ofstream file;
[Link]("[Link]" );
return 0;
}
We have opened the file „[Link]’ to write on it. „[Link]’ file must be created in your
working directory.

The syntax for Closing a file is as follows :


#include<iostmanip>
#include<fstream>
#include<iomanip>
#include<fstream >
using namespace std;
int main()
{
ofstream file;
[Link]("[Link]");
[Link]();
return 0;
}
C++ automatically dose and release all the allocated memory. But a programmer should always
close all the opened files.
-For Reading and Writing on a file:-
we use << and >> to write and read from a file respectively.
#include<iomanip>
#include<fstream>
#include<iostream>
using namespace std;
int main()
{
char text[200];
fstream file;
[Link]("[Link]",ios::out|ios::in);
cout<<"Write text to be written on file."<<endl;
[Link](text,sizeof(text));
//writing on file
file<<text<< endl; //ceding from file
file>>text;
cout<<text<<endl;
//closing the file
file.close0;
return 0;
}

***Overloading the Extraction and Insertion Operators


• Overloading Insertion (<<) and Extraction Operator (>>) must be done by means of friend
functions
• It is considered as binary operator where one argument must be of ostream or istream
compulsorily
Overloading >> Prototype:
friend istream& operator >>(istream&, M&);
• Example:
istream& operator >>(istream& in, M & m)
{ in >> [Link];
return in;
}
int main()
{ M ob;
cin>>ob;
}

Overloading >> & << Example


friend ostream& operator <<(ostream&, M &);
• Example:
ostream& operator <<(ostream& out, M & m)
{ out<< [Link]
return out;
}
int main()
{ M ob;
cout<<ob;
}
#include <iostream>
using namespace std;
class Complex
{ int real, imag;
public:
Complex(int r = 0, int i =0) { real = r; imag = i; }
friend ostream & operator << (ostream &out, const Complex &c);
friend istream & operator >> (istream &in, Complex &c);
};
ostream & operator << (ostream &out, const Complex &c)
{ out << [Link];
out << "+i" << [Link] << endl;
return out;
}
istream & operator >> (istream &in, Complex &c)
{ cout << "Enter Real Part "; in >> [Link];
cout << "Enter Imaginary Part "; in >> [Link];
return in;
}
int main()
{ Complex c1;
cin >> c1;
cout << "The complex object is ";
cout << c1;
return 0;
}
Memory as a Stream Object
• We can use section of memory to store stream object.
• After creating object we can read or write data in stream object more like file.
• It is useful when we need to format the output.
• It is common in calling functions in GUI environment.
• Family of stream classes implements in-memory formatting.
• For writing to memory we use ostrstream class. It is subclass of ostream class only.
• For reading data from memory we use istrstream which is subclass of istream class.
• For reading and writing purpose we can use strstream class.

#include<iostream>
#include<fstream>
#include<iomanip>
#include<strstream>
using namespace std;
const int MAX=80;
int main()
{ char ch = 'a'; int i = 100; double num = 1235.567;
char str1[30] = "abed"; char str2[30] = "efgh"; char buff[MAX];
ostrstream my_object(buff, MAX);
my_object<<"\n ch="<<ch; my_object<<"\n i=" <<i;
my_object<<setiosflags(ios::fixed)<<setprecision(2)<<"\n double=" <<num;
my_object<<"'n first String ="<<str1;
my_object<<"\n Second string="<<str2; cout<<buff;
return 0;
}
*****Command-Line Arguments
• As we know we pass argument to functions.
• Main is also the function which every program have.
• We can pass command line arguments to main function also.
• Arguments can be passed at the time of running the program.
• The syntax for writing main() function with command line arguments is as follows :
int main(int argc, char *argv0);
• In the above statement, argc indicates number of arguments passed to main function whereas
argvn array actually collected the pass arguments. Number of argument count includes program
name also.
• Steps to execute command program are different than normal program.

//Compile the program first on dev cpp editor


//for run go to program folder type on address bar of the folder as cmd
//the write program_name.exe pass the arguments
//example program name is [Link] 1 2 3 4 and then press enter

#include <iostream>
using namespace std;
int main(int argc, char *argv[])
{ for (int i=0; i<argc; i++)
{ cout <<"This is Argument number #"<<i<<"->"<<argv[i]<< endl;
}
return 0;
}
#include <iostream>
#include <cstdlib> // For atoi function
using namespace std;
int main(int argc, char* argv[])
{ //Check if at least 3 arguments are provid (program name + 2 no)
if (argc< 3)
{ cout<< "Usage: " <<argv[0] << " <number1><number2>" ; return 1;
} // Convert the arguments to integers
int number1 = atoi(argv[1]); int number2 = atoi(argv[2]);
int sum = number1 + number2;
int product = number1 * number2;
cout<< "Number 1: " << number1 <<endl;
cout<< "Number 2: " << number2 <<endl;
cout<< "Sum: " << sum <<endl;
cout<< "Product: " << product <<endl;
return 0;
}

Printer output.
• It is easy to use console based program to send data to printer.
• Many special filenames for hardware devices are defined by OS.
• Which makes it possible to treat device like files.
• Hardware device names are as follows :
• con: it is for console
• aur: first serial port
• com2: second serial port
• Iptl: first parallel printer
• Ipt2: second parallel printer
• Ipt3: third parallel printer
• nul: used as dummy device
• Generally. printer is connected to first parallel port of the system.
• So it is recommended to use Ion as filename to print through the printer.
#include<iostream>
#include<fstream>
using namespace std;
int main()
{ cout<<"\n Printing output using printer:";
ofstream print("LPT1");
//provided printer is connected to first parallel port
if(!print)
{ //it will exit with I if printer is not connect
cout<<"\n No printer connected";
return 1;
}
print<<"\n This is first line printed:" ;
print<<"\n Number:"<<12345;
print<<"\n float:"<<345.567;
print<<"\n char: "<<'c';
[Link](); //close printer
return 0;
}

You might also like