Week 13
Week 13
1
C++ Files and Streams
C++ views each files as a sequence of bytes.
Each file ends with an end-of-file marker.
When a file is opened, an object is created and
a stream is associated with the object.
To perform file processing in C++, the header
files <iostream.h> and <fstream.h> must be
included.
<fstream.> includes <ifstream> and
<ofstream>
2
How to open a file in C++ ?
3
File Open Modes
ios:: app - (append) write all output to the end of
file
ios:: ate - data can be written anywhere in the file
ios:: binary - read/write data in binary format
ios:: in - (input) open a file for input
ios::out - (output) open a file for output
ios: trunc -(truncate) discard the files’ contents if
it exists 4
How to close a file in C++?
The file is closed implicitly when a
destructor for the corresponding object is
called
OR
by using member function close:
outClientFile.close();
5
File position pointer
<istream> and <ostream> classes provide
member functions for repositioning the file
pointer (the byte number of the next byte in the
file to be read or to be written.)
These member functions are:
seekg (seek get) for istream class
seekp (seek put) for ostream class
8
//closing the file
file.close();
//again open file in read mode
file.open("sample.txt",ios::in);
//read untill end of file is not found.
char ch; //to read single character
cout<<"File content: ";
while(!file.eof())
{
file>>ch; //read single character from file
cout<<ch;
}
file.close(); //close file
return 0;
9
}
Formative Assessment – Submit with
Example
Constructor vs Destructor
Overloading vs Overriding
Unary vs binary operator
Method in file stream class
10