0% found this document useful (0 votes)
2 views21 pages

C++ File Handing

A file is a collection of information stored on a computer's disk, identified by a unique name. In C++, files can be opened, written to, read from, and closed using specific classes and functions, with various modes for file operations. Error handling for file operations can be performed using functions like is_open(), fail(), and eof() to ensure successful file access and processing.

Uploaded by

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

C++ File Handing

A file is a collection of information stored on a computer's disk, identified by a unique name. In C++, files can be opened, written to, read from, and closed using specific classes and functions, with various modes for file operations. Error handling for file operations can be performed using functions like is_open(), fail(), and eof() to ensure successful file access and processing.

Uploaded by

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

What is a File?

• A file is a collection on information, usually stored on


a computer’s disk. Information can be saved to files
and then later reused.

1
File Names
All files are assigned a name that is used for identification
purposes by the operating system and the user.
Focus on Software Engineering:
The Process of Using a File
• Using a file in a program is a simple three-step process

• The file must be opened.


If the file does not yet exits, opening it means creating it.

• Information is then saved (write)to the file, read from the file, or
both.

• When the program is finished using the file, the file must be
closed.
C++ Files and Streams

Classes for file stream operation


ofstream: Stream class to write on files
ifstream: Stream class to read from files
fstream: Stream class to both read and write from/to files.
These classes are derived directly or indirectly from the classes istream and ostream.
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> and <fstream> must be included.
• <fstream> includes <ifstream> and <ofstream>

5
open a file
The first operation generally performed on an object of one of these classes is to
associate it to a real file. This procedure is known as to open a file.

open (“filename.extension”, mode);


Ofstream outClientFile(“clients.dat”)
OR

Ofstream outClientFile(“clients.dat”, ios:out)


Combining object construction and stream opening in a single statement.
Both forms to open a file are valid and equivalent.

OR
Ofstream outClientFile;
outClientFile.open(“clients.dat”, ios:out) 6
File Open Modes
ios::in Open for input operations.
ios::out Open for output operations.
ios::binary Open in binary mode.
Set the initial position at the end of the file.
ios::ate
If this flag is not set, the initial position is the beginning of the file.
All output operations are performed at the end of the file,
ios::app
appending the content to the current content of the file.
If the file is opened for output operations and it already existed,
ios::trunc
its previous content is deleted and replaced by the new one.

7
Testing for Open Errors

is_open()
• To check if a file stream was successful opening a file

• you can do it by calling to member is_open.

• This member function returns a bool value i.e. true or false.

• True in the case that indeed the stream object is associated with an open file, or false
otherwise:

if ( myfile.is_open() )
{ /* ok, proceed with output */ }
8
Testing for Open Errors
dataFile.open(“cust.dat”, ios::in);
if (!dataFile)
{
cout << “Error opening file.\n”;
}

9
Another way to Test for Open Errors
dataFile.open(“cust.dat”, ios::in);
if ( dataFile.fail() )
{
cout << “Error opening file.\n”;
}

10
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:

myfile.close();
Once this member function is called, the stream object can be
re-used to open another file, and the file is available again to
be opened by other processes.

11
Text file
streams are those where the ios::binary flag is not included in their
opening mode.

These files are designed to store text and thus all values that are input
or output from/to them can suffer some formatting transformations,
which do not necessarily correspond to their literal binary value.
WRITING ON A TEXT FILE
#include <iostream>
#include <fstream>
using namespace std;

int main () {
ofstream myfile ("example.txt");

if (myfile.is_open())
{

myfile << “MY NAME IS SAHER JAWAID\n";


myfile << “I AM LECTURER AT .\n";
myfile << “SIR SYED UNIVERSITY.\n";

myfile.close();
}
else cout << "Unable to open file";
return 0;
}
READING A TEXT FILE
#include <iostream>
#include <fstream>
#include <string>
using namespace std;

int main () {
string line;
ifstream myfile ("example.txt");
if (myfile.is_open())
{
while ( getline (myfile,line) )
{
cout << line << '\n';
}
myfile.close();
}

else cout << "Unable to open file";

return 0;
}
• This last example reads a text file and prints out its
content on the screen.

• We have created a while loop that reads the file line by


line, using getline.

• The value returned by getline is a reference to the


stream object itself, which when evaluated as a Boolean
expression

True

 if the stream is ready for more operations

False

 if either the end of the file has been reached


 if some other error occurred.
while ( ! myfile.eof() )
{
//place the line from myfile into
the
//line variable:

getline (myfile,line);

//display the line we gathered:

cout << line << endl;


}
eof() which stands for "end of file".

• The eof() function is a boolean function

• check whether or not the file has reached the end.

• It returns true when the file is at the end and false


otherwise.
for (int count = 0; count < 4;
count++)
{
dataFile >>
name;
cout << name << endl;
}
for (int count = 0; count < 4;
count++)
{
dataFile >>
name;
cout << name << endl;
}
Checking state flags
bad()
Returns true if a reading or writing operation fails. For example, in
the case that we try to write to a file that is not open for writing or
if the device where we try to write has no space left.

fail()
Returns true in the same cases as bad(), but also in the case that a
format error happens, like when an alphabetical character is
extracted when we are trying to read an integer number.
eof()
Returns true if a file open for reading has reached the end.

good()
It is the most generic state flag: it returns false in the same cases in
which calling any of the previous functions would return true. Note
that good and bad are not exact opposites (good checks more
state flags at once).
clear()
can be used to reset the state flags.

You might also like