C++ File and Stream Handling Guide
C++ File and Stream Handling Guide
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.
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.
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‟);
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;
}
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. 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;
}
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;
}
#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.
The only difference is that you use an ofstream or fstream object instead of the cout object.
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
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.
• 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.
eof( ) Returns true (non zero value) if end-of-file is encountered while reading otherwise returns false
(zero).
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;
}
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.
#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.
#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;
}