Sunteți pe pagina 1din 32

DATA FILE HANDLING

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.
In C++ file I/O is achieved through a component
header file called fstream.h
At lowest level in C++ file is interpreted as
sequence , or stream, of bytes.
At user level a file consists of a sequence of
intermixed data types characters, arithmetic
values etc.
The I/O library manages two aspects- as interface
and for transfer of data.
INTRODUCTION
The fstream library predefine a set of operations
for handling all file related input/output through
certain classes.
Stream Classes required for File I/O :
ifstream:- Stream class to read from files
ofstream:- Stream class to write on files.
fstream:- Stream class to both read and write from/to
files
ios is the base class.
istream and ostream inherit from ios
ifstream inherits from istream (and ios)
ofstream inherits from ostream (and ios)
iostream inherits from istream and ostream (& ios)
fstream inherits from ifstream, iostream, and ofstream
Classes for Stream I/O in C++
STREAM I/O
The stream that supplies data to the program is
known as input stream
The stream that receives data from the program
is known as output stream
File Program ( Input stream) - reads data from file
Program File (Output stream) write data to file
All designed into fstream.h and hence needs to be
included in all file handling programs.
6
IFSTREAM
Input file stream Class
It provide input operation for file
open() is a member function of the class ifstream
Inherited functions of ifstreamclass, from the class
istreamare:-
Text File
get()
getline()
Binary File
read()
For supporting random access
seekg()
tellg()
OFSTREAM
Output file stream Class
It provide output operation for file provide
open() is a member function of the class ofstream
Inherited functions of ofstream class, from the class
ostream are
Text file
put()
Binary File
write()
Random access
seekp()
tellp()
FSTREAM
It supports files for simultaneous input and
output
fstream is derived from
ifstream
ofstream
iostream
They are parent classes and fstreamis the
child class
DATA FILES
Requirement of files
Convenient way to deal large quantities of data.
Store data permanently (until file is deleted).
Avoid typing data into program multiple times.
Share data between programs.
1. Text file : A text file stores information in
ASCII characters. Each line terminated by
EOL ( end of line).
2. Binary file : It stores information in the same
format in which the information is held in
memory. No delimiter for line. no translation
occurs. It is faster and easier for a program
read and write.
OPENING AND CLOSING FILES
Using Constructor:
ifstream input_file(DataFile);
char ch;
Input_file>>ch;
float amt;
input_file>>amt;
ofstream output_file(DataFile);
input_file.close( );
output_file.close( );
DataFile
Input stream
input_file
Program
OPENING AND CLOSING FILES
ofstream output_file(DataFile);
Opening a file for output using stream class
constructor creates a new file if there is no file of
that name on the disk. However , if the file by that
name exists already, the act of opening it for
output scraps it off so that output starts a fresh line
Closing file :-
input_file.close( );
output_file.close( );
Close() does not eliminate the stream; it just
disconnects from the file.
OPENING FILES
Using open() method
STREAM-OBJECT.open(FILENAME, mode)
Eg:-
ofstreamOFILE;
OFILE.open(DATA1.TXT);
ifstreamIFILE;
IFILE.open(DATA2.TXT);
FILE MODES
The File mode describes how a file is to be used:-
File mode
parameter
Description Stream
Type
ios::in Open file to read ifstream
ios::out Open file to write. If the file exists then, previous
content is discarded else new file is created.
ofstream
ios::app All the data you write, is put at the end of the file. It
calls ios::out
ofstream
ios::ate All the date you write, is put at the end of the file. It
does not call ios::out. I/O operations can occur
in anywhere in the file
ofstream/
ifstream
ios::trunc Deletes all previous content in the file. (empties the
file)
ofstream
ios::nocreate If the file does not exists, opening it with the open()
function gets impossible.
ofstream
ios::noreplace If the file exists, trying to open it with the open()
function, returns an error.
ofstream
ios::binary Opens the file in binary mode. ofstream/
ifstream
FILE MODES
All the flags can be combined using the
bitwise operator OR (|). For example, if we
want to open the file example.bin in
binary mode to add data we could do it by
the following call to member function
open():
fstreamFILE;
FILE.open ("EXAMPLE.BIN", ios::out | ios::app | ios::binary);
STEPS TO PROCESS A FILE
Determine the type of link required.
Declare a stream for the desired type
of link.
Attach the desired file to the stream.
Now process as required.
Close the file-link with stream.
STEPS TO PROCESS A FILE IN YOUR
PROGRAM
Determine the type of link required.
File to memory Input
Memory to File Output
Both Input/Output
If data is to be brought in from file to memory,
then link is of type file to-memory
If data is to be sent from memory to file, then
the link is memory-to-file
STEPS TO PROCESS A FILE IN YOUR
PROGRAM
Declare a stream for the desired type of link.
In order to create file streams, include the header
file fstream.h
File to memory (IN TO the memory) ifstreamfin
Memory to File(OUT FROM memory) ofstreamfout
Both fstream finout
STEPS TO PROCESS A FILE IN YOUR
PROGRAM
3. Attach the desired file to the stream.
ifstreamfin(data.dat); //using constructor
Or
fin.open(data.dat, ios::in); //using open
ofstreamfout(data.dat); //using constructor
Or
fout.open(data.dat, ios::out); //using open
fstreamfinout(data.dat); //using constructor
Or
finout.open(data.dat, ios::in | ios::out); //using open
STEPS TO PROCESS A FILE IN YOUR
PROGRAM
Now process as required.
#include<fstream.h>
void main( )
{ofstream fout;
fout.open(mark.dat, ios::out);
char ans=y;
int rollno;
while(ans==y || ans==Y)
{
cout<<\nEnter roll no : ;
cin>>rollno;
fout<<rollno;
cout<<\n Want to enter more? :;
cin>>ans;
}
fout.close( );
}
STEPS TO PROCESS A FILE IN YOUR
PROGRAM
5. Close the file-link with stream.
fin.close( );
fout.close( );
OBJECTIVE : TO INSERT SOME DATA ON A
TEXT FILE
Program file SCREEN
File (.txt, .dat)
#include<fstream>
int main()
{
ofstream fout;
fout.open("abc.txt");
fout<<"This is my first program in file handling";
fout<<"\n Hello again";
fout.close();
return 0;
}
READING DATA FROM A TEXT FILE
#include<fstream>
#include<iostream>
#include<conio.h>
int main()
{
ifstream fin;
char str[80];
fin.open("abc.txt");
fin>>str; // read only first string from file
// as spaces is treated as termination point
cout<<"\n From File :"<<str ;
getch();
return 0;
}
NOTE : To overcome this problem use
fin.getline(str,79);
DETECTING END OF FILE
Using EOF( ) member function Using filestream object
Syntax
Filestream_object.eof( );
Example
#include<iostream>
#include<fstream>
#include<conio.h>
int main()
{
char ch;
ifstream fin;
fin.open("abc.txt");
while(!fin.eof())
// using eof() function
{
fin.get(ch);
cout<<ch;
}
fin.close();
getch();
return 0;
}
Example
// detecting end of file
#include<iostream>
#include<fstream>
#include<conio.h>
int main()
{
char ch;
ifstream fin;
fin.open("abc.txt");
while(fin) // file object
{
fin.get(ch);
cout<<ch;
}
fin.close();
getch();
return 0;
}
TO READ THE CONTENTS OF A TEXT FILE
AND DISPLAY THEM ON THE SCREEN
Program ( using getline member
function)
Program ( using get( ) member
function)
#include<fstream>
#include<conio.h>
#include<iostream>
int main()
{
char str[100];
ifstream fin;
fin.open("c:\\abc.txt");
while(!fin.eof())
{
fin.getline(str,99);
cout<<str;
}
fin.close();
getch();
return 0;
}
#include<fstream>
#include<conio.h>
#include<iostream>
int main()
{
char ch;
ifstream fin;
fin.open("file6.cpp");
while(!fin.eof())
{
fin.get(ch);
cout<<ch;
}
fin.close();
getch();
return 0;
}
BASIC MODEL FOR FILE I/O
The file stream classes are simply be viewed as a
stream or array of uninterpreted bytes. That is, it
is like an array of bytes stored and indexed from
zero to len-1, where len is the total number of bytes
in the entire file.
Each open file has two positions associated with it:
The current reading position, which is the index of the
next byte that will be read from the file. It simply points
to the next character that the basic get method will
return.
The current writing position, which is the index of the
byte location where the next output byte will be placed.
It simply points to the location where the basic put
method will place byte(s).
INPUT OUTPUT OPERATIONS
Repositioning with the get and put stream pointers
All i/o streams objects have, at least, one internal stream
pointer:
For input streams like, ifstreamand istream, you use get to
move the pointer that points to the element to be read
in the next input operation.
For output streams, like ofstreamand ostream, you use the
put pointer that points to the location where the next
element has to be written.
Recall that fstream, inherits both, the get and the put
pointers, from iostream(which is itself derived from both
istreamand ostream).
These internal stream pointers that point to the reading or
writing locations within a stream can be manipulated using
member functions.
RANDOM ACCESS
tellg() and tellp()
tellp( )
It return the distance of writing pointer from the beginning
in bytes
Syntax
Fileobject.tellp( );
Example:
long n = fout.tellp( );
tellg( )
It return the distance of reading pointer from the beginning
in bytes
Syntax
Fileobject.tellg( );
Example:
long n = fout.tellg( );
RANDOM ACCESS
seekg() and seekp()
You may change the position of the get and put stream
pointers using seekg() and seekp() functions.
Both functions are overloaded with two different
prototypes. The first prototype is:
seekg ( position );
seekp ( position );
The other prototype for these functions is:
seekg ( offset, direction );
seekp ( offset, direction );
ERROR HANDLING IN FILES
The fail() function returns true (non-zero) if an error
has occurred with the current stream, false(zero)
otherwise. This can be used for checking whether the
previous operation has failed.
Examples of failures that cause fail to be set:
file not found (when opening for reading).
file cannot be created (when opening for writing).
end of file is reached before the requested data could be
read.
invalid formatting of data (e.g. letters when expecting
numbers).
ERROR HANDLING IN FILES
The bad() function returns true((non-zero) if a
fatal error with the current stream has
occurred, false(zero) otherwise.
Note: fatal errors do not normally occur. Even a
failure to open a file is not a fatal error.
The function eof() returns true((non-zero) if the
end of the associated input file has been
reached, false (zero)otherwise.
The function good() returns true((non-zero) if no
errors have occurred with the current stream,
false (zero)otherwise.
The function clear() does two things:
it clears all io_stream_state_flags associated with the
current stream, and sets the flags
DIFFERENCE BETWEEN GET() AND GETLINE() FUNCTION
Both get() and getline() can read characters from
the input stream into an array till the specified
number of characters are entered or till the
delimiting character is encountered( \n by
default). The difference is that, in case of getline()
this character is removed from the input stream
but get() leaves it in the input stream.

S-ar putea să vă placă și