0% found this document useful (0 votes)
116 views

File Handling in C++: By: Haya Majid Qureshi BS (CS) - II

1) C++ provides file handling capabilities through classes like ifstream, ofstream and fstream that allow opening, reading, writing and closing of files. 2) To open a file, a file stream object is created and its open() member function is called, specifying the file name and mode. Files can also be opened using file stream constructors. 3) Reading from files uses the extraction operator >> and writing uses the insertion operator << similarly to console input/output. This document discusses various C++ file handling concepts like opening, closing, reading and writing to both text and binary files as well as using file pointers and checking for end of file.

Uploaded by

fairy178
Copyright
© Attribution Non-Commercial (BY-NC)
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)
116 views

File Handling in C++: By: Haya Majid Qureshi BS (CS) - II

1) C++ provides file handling capabilities through classes like ifstream, ofstream and fstream that allow opening, reading, writing and closing of files. 2) To open a file, a file stream object is created and its open() member function is called, specifying the file name and mode. Files can also be opened using file stream constructors. 3) Reading from files uses the extraction operator >> and writing uses the insertion operator << similarly to console input/output. This document discusses various C++ file handling concepts like opening, closing, reading and writing to both text and binary files as well as using file pointers and checking for end of file.

Uploaded by

fairy178
Copyright
© Attribution Non-Commercial (BY-NC)
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/ 28

File Handling in

C++
By:
Haya Majid Qureshi
BS(CS)-II
Introduction
• Computer programs are associated to work with
files as it helps in storing data & information
permanently.

• File - itself a bunch of bytes stored on some


storage devices.

• The library predefine a set of operations for all


file related handling through certain classes.
C++ STREAMS
• A stream is general name given to the flow of
data.
• In C++ a stream is represented by an object of
a particular class , i.e cin and cout.
In another words,
 File  Program ( Input stream) - reads-extract
 Program  File (Output stream) – write-insert
FLOW OF DATA…
DATA
Program
Input Output
Stream Stream
>> <<
(Extraction (Insertion
operator) Operator)

Files
istream class DATA ostream class
ACCESS TO FILE I/O

• ifstream
• ofstream
• fstream
The Stream Class Hierarchy
ios

Istream Ostream
iostream
Get() Put()
Read() Write()
>> <<

fstream

Ifstream Ofstream
Open() Open()
fstreambase Tellp()
Tellg()
Seekg() Seekp()
File Handling Hierarchy
DIFFERENT FILE OPERATION
• OPENING A FILE
• CLOSING A FILE
• READING FROM A FILE
• WRITING ON A FILE
• CHECKING FOR END OF FILE
OPENING A FILE
• For opening a file, we must first create a file
stream and than link it to the filename.
A file can be opened in two ways:
• Using the constructor function of the class.
This method is useful when we open only
one file in the stream. 

• Using the member function open() of the


class. This method is used when we want to
manage multiple files.
USING MEMBER FUNCTION
• In order to open a file with a stream object we use
its member function open():
open (“const char*filename”, mode);

 filename – file to open (full path or local)


 mode – how to open (1 or more of following --

using I).

Mode is an optional parameter with a combination


of the following flags:
Contd…
 ios::left – left-adjust output
 ios::right – right-adjust output
 ios::in / ios::out – (the defaults of ifstream and
ofstream)
 ios:nocreate / ios::noreplace – open only if the file
exists / doesn’t exist
 ios::trunc – open an empty file
 ios::binary – open a binary file (default is textual)

Example :

ofstream myfile;
myfile.open ("example.bin", ios::out | ios::trunc |ios::in);
USING CONSTRUCTOR
•  A constructor that automatically calls
the open() member function and has the exact
same parameters as this member.
• operation in our previous example by writing:

ofstream myfile ("example.bin", ios::out |


ios::app | ios::binary);

• To close the file using the method “close()”.


myfile.close();
Contd…

– we can use our file streams the same way we


are already used to use cin and cout, with the
only difference that we have to associate
these streams with physical files.
Example
#include <iostream>
#include <fstream>
void main ()
{
ofstream myfile;
myfile.open ("example.txt");
myfile << "Writing this to a file.\n";
myfile.close();
return 0;
}
……

1: To access file handling routines:


#include <fstream.h>
2: To declare variables that can be used to access file:
ifstream in_stream;
ofstream out_stream;
3: To connect your program's variable (its internal name) to
an external file
in_stream.open("infile.dat");
out_stream.open("outfile.dat");
4: To see if the file opened successfully:
if (in_stream.fail())
{ cout << "Input file open failed\n"; }
…..

5: To get data from a file (one option), must declare a variable to


hold the data and then read it using the extraction operator:
int num;
in_stream >> num;
[Compare: cin >> num;]
6: To put data into a file, use insertion operator:
out_stream << num;
[Compare: cout << num;]
NOTE: Streams are sequential – data is read and written in order
.
7: When done with the file:
in_stream.close();
out_stream.close();
Stream State Member Function
• In C++, file stream classes inherit a stream state
member from the ios class, which gives out the
information regarding the status of the stream.
For instance:
eof() –end of file character.
fail()- status of file at opening for I/O.
bad()-invalid file operations or unrecoverable
error .
good()-previous file operation has been
successful.
TYPES OF FILES
• The two basic types are:
– TEXT
– BINARY
Contd…
• A text file consists of readable characters .
• A binary file stores data to disk in the same form
in which it is represented in main memory.
• For the binary file we will use write to write to
the file, whereas for the text file we will use the
usual output operator(<<).
• With the binary file we will use the read function
to read record, but with the text file we will use
the usual input operator(>>).
Reading and Writing to Binary files
• File streams include two member functions
specifically designed to input and output binary
data sequentially: write and read.
• The first one (write) is a member function of
ostream inherited by ofstream.
• And read is a member function of istream that is
inherited by ifstream. 
write ( memory _ block, size );
read ( memory _ block, size );
Character I/O
• To write:
– put() – writing single character.

outfile.put(ch);

• To read:
– get() – reading a single character .
– getline() – reading a single line.

infile.get(ch);
Stream Pointer
• All i/o file maintains atleast one internal pointers:
get _ pointer and put _ pointer
• They enable to attain the random access in file
otherwise which is sequential in nature.

• By default reading pointer is set at the beginning


and writing pointer is set at the end (when you
open file in ios::app mode)
FUNCTION ASSOCIATED WITH FILE POINTER
• tellg() and tellp()
• These two member functions have no
parameters.
• return a value of an integer data type
representing the current position.
allow you to set and examine the
• get stream pointer (in the case of tellg)
• put stream pointer (in the case of tellp).
Contd…
• seekg() and seekp()
Both functions are overloaded with two different prototypes. The first
prototype is:

seekg ( position );Moves get pointer (input) to a specified location.


seekp ( position );Moves put pointer (output) to a specified location.

infile.seekg(10);

Moves the file pointer to the byte number 10.

The bytes in a file are numbered beginning from zero.

Thus, the pointer will be pointing to the 11th byte in the file.
Contd…
• The other prototype for these functions is:

seekg ( offset, direction );


seekp ( offset, direction );

The parameter offset represents the number of bytes.

The parameter direction specified the location. 

The direction takes one of the following these constant defined in


the ios class.
Contd…
• ios::beg (counted from the beginning of
the stream)
• ios::cur (counted from the current position
of the stream)
• ios::end(counted from the end of the
stream)
Example
// obtaining file size
#include <iostream>
#include <fstream>
int main () {
long begin,end;
ifstream myfile ("example.txt");
begin = myfile.tellg();
myfile.seekg (0, ios::end);
end = myfile.tellg();
myfile.close();
cout << "size is: " << (end-begin) << " bytes.\n";
return 0;
}
EOF and File I/O within Function
• When using a file within a function, the file parameter must
be a reference parameter:
int read_file(ifstream& infile);
• As with keyboard input, it is often desirable to process
some unknown amount of data. We use the end-of-file
(EOF) to accomplish this. EOF is automatically included in
text files we create.
in _ stream >> num; // for read
while (! in_stream.eof())
{loop body
in _ stream >> num;}

You might also like