You are on page 1of 11

Unit IV

Working with files

Introduction:

o Files are used to store data in a storage device permanently.


o File handling provides a mechanism to store the output of a program in a file and to perform
various operations on it.
o A stream is an abstraction that represents a device on which operations of input and output are

performed.
o A File is a collection of related data stored in a particular area on the disk.
o Data transfer between console unit and the program.
o Data transfer between the program and a disk.

Streams:
o Stream is a sequence of bytes.
o If use file stream as an interface between the program and files.

Files and Streams:

o We are using the iostream standard library, it provides cin and cout methods
for reading from input and writing to output respectively.
o To read and write from a file we are using the standard C++ library
called fstream.
o Let us see the data types define in fstream library is:

classes for file Stream Operations:


o in C++ input and output is performed in the form of sequence of bytes or more
commonly known as stream.
o C++ come with libraries which provide us with many way for performing
input and output.
o Input Stream: in the direction of flow of bytes is from the device(for example
, keyboard)to the main memory then this process is called input.
o Output Stream: in the direction of flow of bytes is opposite i.e from main
memory to device(display screen) then this process is called output.

o Types of Stream available in C++.


1. Text Stream
2. Binary Stream

1.Text Stream:
o Text Stream sequence of characters.
o The stream holds the same character that we see the stream data is displayed.
o Only a few special character like new line ,tab etc.are stored according to the system.
o So there may not be direct one to one relationship between character in the device file
and character that are read and write.

2.Binary Stream:
o Binary Stream is a collection of bytes.
o Binary Stream has one to one relationship between byte in the stream and the device
file.
o The number byte in a file and number of byte in a device file are same.
o Stream can be further divided in to Input stream and Output stream.
o A program can read data from input stream.
o A program can write data from output stream.

Hearder file available in C++ for Input/Output operations are:

1.iostream:
o iostream for standard input output stream.
o This header file contain definition to object like cin , cout , cerr etc,

2.iomanip:
o iomanip stand for input output manipulator. the method declared in file this file are
used for manipulating stream.
o This file contain definition of setw, set precision etc.

3.fstream:
o This data type represents the file stream generally, and has the capabilities of both ofstream and
ifstream which means it can create files, write information to files, and read information from
files.
o The two keyword cout and cin in C++are used very often for printing output and taking input
respectively .

o these two are the most basic method of taking input printing output in C++.to use cin and cout in
C++ one most include the header file iostream in the program.

1. Standard output stream (cout):


o Usually the standard output device is the display screen.
o The C++ cout statement is the instance of the ostream class.
o It is used to produce output on the standard output device which is usually
the display screen.
o The data needed to be displayed on the screen is inserted in the standard
output stream (cout) using the insertion operator(<<).

2. standard input stream (cin):


o Usually the input device in a computer is the keyboard.
o C++ cin statement is the instance of the class istream and is used to read
input from the standard input device which is usually a keyboard.
o The extraction operator(>>) is used along with the object cin for reading
inputs.
o The extraction operator extracts the data from the object cin which is
entered using the keyboard.

3. Un-buffered standard error stream (cerr):


o The C++ cerr is the standard error stream that is used to output the errors.
o This is also an instance of the iostream class.
o As cerr in C++ is un-buffered so it is used when one needs to display the
error message immediately.
o It does not have any buffer to store the error message and display it later.

#include <iostream>

using namespace std;

int main()
{
cerr << "An error occurred";
return 0;
}
4. 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.

Disk file i/o with streams: opening and closing file:

o File is a collection of related data stored in some storage device like Disk
,pen drive, CD etc.
o Every file stored in any device is associated with file name.
o File name is made up of name and extension.
o File means storing data in computer device.
o To process /add data in a file we need to open the file
o C++ provides set of classes ,with there functions, for handling file in our
programs.
o To open a file we create object of the required class.
o Then we open a file using some open() function of the class.

Syntax:

open (FileName,Mode);

o FileName is a string that mention full file name with its parent folder path.
o If the program and the file to open are in same folder ,then only filename is
enough.
o Mode is an int value that specifies the mode e.g read and write mode.
o The mode are predefined in ios class ,of Stream class hierarchy.
o Mode is optional ,and its value is assumed by compiler according the class used.
e.g. To open file for reading,
ifstream fin; //object if ifstream
fin.open (“mydata.txt”). //open the file

(default input mode)


o To close a file ,we use close the file using close() function
fin.close();
o The close() function save the data to actual file then close the file.
o some classes of file

Sr.No Class Contents


1 fstreambase Provides operations common to the file stream.
Serves as a base for fstream and if stream class.
Contains open() and close() functions.
2 if stream Provides input operations and Contains open() with default input
mode.
Inherit the function get(), getline(), seekg(), tellg() from istream.
3 of stream Provides output operations and Contains open() with default
output mode.
Inherit put(), seekp(),tellp() and write() function from ostream.
4 fstream Provides support for simultaneous input and output operations.
Contains open() with default input mode. Inherit all the function
from istream and ostream classes through iostream.

Using above classes and their function one can perform following operation on file.
o Open a file. Existing file can be open and new file can be created.
o Read, write or modify data in file
o Save data in the file
o Close the file
o
Detecting End _Of_File(EOF):
eof():while reading the content of file sequentially, one has to check whether end of file is
reached.
end of file C++ provide a functions eof()which return true (i.e. 1)if end of file is
reached,else return false(i.e. 0).

e.g.
if(!obj.eof())
{
Statements;
}

Different File Mode:


o When a file opened we mention file name and mode in which the file is to be used.
o When file name is a string ,mode ia an int (it is optional parameter )with a
combination of the following flag:

ios::in Open for input operation


ios::out Open for output operation
ios::binary Open for binary operation

ios::ate Set the initial position at the end of the file.


In this flag is not set, the initial position is the beginning of the file.
ios::app All output operations are performed at the end of file ,appending the content to
the current content of the file.
ios::trunc If the file is open for output operation and it alredy existed ,its previous content
is deleted and replaced by new one.
o All the flag can be combined using the bitwise operator OR( | ).
o Example:

ofstreamfout;

fout.open (“example .txt”,ios::out | ios::app);

o Each of the open member function of classes of stream ,if stream and f stream has a
default mode that is used if the file is opened without a second argument.

class default mode parameter


of stream ios::out
if stream ios::in
fstream ios::in | ios::out

File Pointer and Manipulator:


o The C++ I/O system support for function for setting a file pointer to any desired position
inside the file or to get the file pointer.
o These allow the programmer to have control over a pointer in the file where read or write
operation text place. These for function are listed below.

o The seekp() and tellp() are member function of ofstream. The seekg() or tellg() are
member function of ifstream. The class fstream deals with file in both input and output
modes.
o Hence, there are two file pointer in class fstream and the put pointer used for writing and
get pointer used for the reading.

1. seekg():
o The function is used to position the get-pointer at given distance from given starting
point.
Syntax:
seekg(int offset,int start);

o The start part mention from where to count offset.


o It is defiend by C++ as follows it may take any following constant values:

value offset is relative to..


ios::beg Beginning of the stream
ios::cur Current position in the stream
ios::end End if the stream

e,g. obj.seekg(10, ios::cur);

2. seekp():
o The function is used to place the put-pointer at the given distance from string pointer.

seekp(int offset,int start);

o The start part mention from where to count offset

e,g. obj.seekp(-5, ios::cur);

o place the put –pointer 5 character behind its current position.

3. tellg():
o the function is used to get the current position of get pointer.
Syntax:
int tellg();
e,g. int p = obj.tellg();

4. tellp():
o the function is used to get the current position of put pointer.
Syntax:
Int tellp();
e,g. int p =obj.tellp();
o for working with ‘get’ pointer(for seekg and tellg)file must have read mode.
o for working with ‘put’ pointer(for seekp and tellp)file must have write mode.

o I/O Manipulators are formatting instruction inserted directly into a stream.


o endl is also manipulator that sends a newline to the stream and flushes it.

cout<<”This line is printed as it is and the next out put

will be printed on next line.”<<endl;

setiosflags()manipulator:

cout<<” setiosflags(ios::fixed)// use fixed decimal points

<< setiosflags(ios::showpoint)// always show decimal point

<<var;

o Note that manipulator affect only the data follows them in the stream i.e. formatting
effects to the I/O that is coming after they are used in the code ,not the data that come
before them.
o Few of the I/O manipulator are as below.

Functions Use
setw() Set field width for output.
setprecision() Set precision(number of digit displayed)
setfill() Set fill character for output (default is a space)
setiosflags() Set specified flags
resetiosflags() Clear specified flags

Updating File:
consider a text field has content :test1.txt
abc
123
Pqr
456
Stu
789
Lmn
012
And you want to update “stu” number from 789 to 276.

#include<iostream>
#include<fstream>
#include<string>
#include<cstdio>

using namespace std;

int main()
{
string x;
ifstream file ("test1.txt");
ofstream ofile ("test2.txt");
cout<<remove<<endl;

while(!file.eof())
{
getline(file,x);

if(x=="789")
{
ofile<<"276"<<endl;

}
else
{

ofile<<x<<endl;
}
}
file.close();
ofile.close();
remove("test1.txt");
return 0;
}
Out Put:
abc
123
Pqr
456
Stu
276
Lmn
012

Error Handling in File I/O


o we have assumed that the files we opened for reading already existed,
and that those opened for writing could be created or appended to.
o We’ve also assumed that there were no failures during reading or writing.
o There are many error possible while we are with file.
o In a real program it is important to verify such assum ptions and take
appropriate action if they turn out to be incorrect.
o A file that you think exists may not,or a filename that you assume you can
use for a new file may already apply to an existing file.
o Or there may be no more room on the disk, or no disk in the drive, and so
on.

#include <fstream> //for file streams


#include <iostream>
using namespace std;
#include <process.h> //for exit()
const int MAX = 1000;
int buff[MAX];
int main()
{
for(int j=0; j<MAX; j++) //fill buffer with data
buff[j] = j;
ofstream os; //create output stream
//open it
os.open(“a:edata.dat”, ios::trunc | ios::binary);
if(!os)
{ cerr << “Could not open output file\n”; exit(1); }
cout << “Writing...\n”; //write buffer to it
os.write( reinterpret_cast<char*>(buff), MAX*sizeof(int) );
if(!os)
{ cerr << “Could not write to file\n”; exit(1); }
os.close(); //must close it
for(j=0; j<MAX; j++) //clear buffer
buff[j] = 0;
ifstream is; //create input stream
is.open(“a:edata.dat”, ios::binary);
if(!is)
{ cerr << “Could not open input file\n”; exit(1); }
cout << “Reading...\n”; //read file
is.read( reinterpret_cast<char*>(buff), MAX*sizeof(int) );
if(!is)
{ cerr << “Could not read from file\n”; exit(1); }
for(j=0; j<MAX; j++) //check data
if( buff[j] != j )
{ cerr << “\nData is incorrect\n”; exit(1); }
cout << “Data is correct\n”;
return 0;
}

You might also like