File Handling in C++1
Transcript of File Handling in C++1
-
8/6/2019 File Handling in C++1
1/28
File Handling in
C++By:
Haya Majid QureshiBS(CS)-II
-
8/6/2019 File Handling in C++1
2/28
IntroductionComputer programs are associated to work withfiles as it helps in storing data & informationpermanently.
File - itself a bunch of bytes stored on somestorage devices.
The library predefine a set of operations for allfile related handling through certain classes.
-
8/6/2019 File Handling in C++1
3/28
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
-
8/6/2019 File Handling in C++1
4/28
FLOW OF DATA
Program
Files
DATA
OutputStream
>>>
(Extractionoperator)
-
8/6/2019 File Handling in C++1
5/28
ACCESS TO F ILE I/ O
ifstream
ofstreamfstream
-
8/6/2019 File Handling in C++1
6/28
The Stream Class Hierarc hy
ios
OstreamPut()
Write()>
IfstreamOpen()Tellg()
Seekg()
iostream
fstream
fstreambase
-
8/6/2019 File Handling in C++1
7/28
File Handling Hierarchy
-
8/6/2019 File Handling in C++1
8/28
DIFFERENT FILE OPERATION
OPENINGA FILE
CLOSINGA FILE
READING FROM A FILEWRITING ONA FILE
CHECKING FOR END OF FILE
-
8/6/2019 File Handling in C++1
9/28
For opening a file, we must first create a filestream 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 onlyone file in the stream.
Using the member function open() of theclass. This method is used when we want tomanage multiple files.
OPENINGA FILE
-
8/6/2019 File Handling in C++1
10/28
USING MEMBER FUNCTIONIn order to open a file with a stream object we useits 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 combinationof the following flags:
-
8/6/2019 File Handling in C++1
11/28
Contd
ios::left left-adjust outputios::right right-adjust outputios::in / ios::out (the defaults of ifstream andofstream)
ios:nocreate / ios::noreplace open only if the fileexists / doesnt existios::trunc open an empty fileios::binary open a binary file (default is textual)
E xample :
ofstream myfile;myfile.open ("example.bin", ios::out | ios::trunc |ios::in);
-
8/6/2019 File Handling in C++1
12/28
USING CONSTRUCTOR
A constructor that automatically callsthe open() member function and has the exactsame 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();
-
8/6/2019 File Handling in C++1
13/28
Contd
we can use our file streams the same way weare already used to use cin and cout, with theonly difference that we have to associatethese streams with physical files.
-
8/6/2019 File Handling in C++1
14/28
E xample# include # include void main ()
{ofstream myfile;myfile.open ("example.txt");myfile
-
8/6/2019 File Handling in C++1
15/28
1 : To access file handling routines:#include
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 filein_stream.open("infile.dat");
out_stream.open("outfile.dat");4 : To see if the file opened successfully:if (in_stream.fail())
{ cout
-
8/6/2019 File Handling in C++1
16/28
..5 : To get data from a file (one option), must declare a
variable to hold the data and then read it using theextraction operator:int num;
in_stream >> num;[Compare: cin >> num;]
6 : To put data into a file, use insertion operator:out_stream
-
8/6/2019 File Handling in C++1
17/28
Stream State Member Function
In C++, file stream classes inherit a stream statemember from the ios class, which gives out theinformation 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.
-
8/6/2019 File Handling in C++1
18/28
TYPES OF F ILES
The two basic types are: TEXT BINARY
-
8/6/2019 File Handling in C++1
19/28
Contd
A text file consists of readable characters .A binary file stores data to disk in the same formin which it is represented in main memory.
For the binary file we will use write to write tothe file, whereas for the text file we will use theusual output operator().
-
8/6/2019 File Handling in C++1
20/28
R eading and Writing to Binaryfiles
File streams include two member functionsspecifically designed to input and output binarydata 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 );
-
8/6/2019 File Handling in C++1
21/28
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);
-
8/6/2019 File Handling in C++1
22/28
S tream Pointer
All i/o file maintains atleast one internal pointers:
get _ pointer and put _ pointer
They enable to attain the random access in fileotherwise which is sequential in nature.
By default reading pointer is set at the beginningand writing pointer is set at the end (when youopen file in ios::app mode)
-
8/6/2019 File Handling in C++1
23/28
FUN CTION ASSO CIATED W ITH F ILEPO IN TER
tellg() and tellp()These two member functions have noparameters.return a value of an integer data typerepresenting 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).
-
8/6/2019 File Handling in C++1
24/28
Contdseekg() and seekp()Both functions are overloaded with two different prototypes. Thefirst prototype is:
seekg ( position ); Moves get pointer (input) to a specifiedlocation.seekp ( position ); Moves put pointer (output) to a specifiedlocation.
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.
-
8/6/2019 File Handling in C++1
25/28
ContdThe 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 constantdefined in the ios class.
-
8/6/2019 File Handling in C++1
26/28
Contd
ios::beg (counted from the beginning of the stream)
ios::cur (counted from the current positionof the stream)ios::end(counted from the end of thestream)
-
8/6/2019 File Handling in C++1
27/28
Examp le // obtaining file size
#include #include int main () {long begin,end;
ifstream myfile ("example.txt");begin = myfile.tellg();myfile.seekg (0, ios::end);end = myfile.tellg();
myfile.close();cout
-
8/6/2019 File Handling in C++1
28/28
EO F and File I/ O within Function
When using a file within a function, the file parameter mustbe a reference parameter:
int read_file(ifstream& infile);As with keyboard input, it is often desirable to processsome unknown amount of data. We use the end-of-file(E OF) to accomplish this. E OF is automatically included intext files we create.
in _ stream >> num; // for read
while (! in_stream.eof()){loop body
in _ stream >> num;}