You are on page 1of 33

Welcome !!!

To the
Presentation on

Created by

Bishnu Nayak

Data File Handling

In this chapter

Introduction.
2. The fstream.h Header File.
3. Data Files.
4. Opening and Closing File.
5. Steps to Process a File in Our Program.
6. Changing the behavior of Streams.
7. Sequential I/O with Files.
8. Detecting EOF.
9. File pointer and Random Access.
10.Basic Operations on Binary Files.
11.Error Handling During File I/O.
12.Quick revision
1.

1.Introduction
Q: What is a File?

Most computers works with files as Files


help in storing information permanently.
Word processors create documents files of
information. Compiler reads source files
and generate executable files. So , we see,
it is the files that are mostly worked with,
inside program. A file itself is a branch of
bytes stored on some storage device like
tape or magnetic disks etc.

2. The fstream.h Header


File.
In
C++, files input/ output facilities are

implemented through a component header file of


C++ standard library. This header file is
fstream.h.
The fstream.h library predefines a set of
operations a set of operations for handing file
related input and output.
For example,
ifstream class ties a file to the program for input;
ofstream class ties a file to the program for
output; and
fstream class ties a file to the program for both
input and output.

A stream is a sequence of
bytes

A stream is a general name given to a


flow of data.
The stream that supplies data to the
program is known as input stream.
It reads the data from the file and
hands it over to the program.
The stream that receives data from the
program is known as output stream.
It writes the received data to the file.

Output stream

DISK FILE

M
e
m
o
r
y

File
to
M
e

To

m
o
r
y

File

Bishnu nayak

iostream.h file

Pointer

streamb
uf

ios

istream

ostream
iostream.
h

fstream.h file

ifstrea
m

fstream
fstreamba
se

ofstrea
m

filebuf

Functions of file Stream Classes.


1. ifstream: It provide input operations. Contains open()
with default input mode. It inherits the functions
get(), getline(), read(), seekg() and tellg() from
istream.
2. ofstream: It provide output operations. Contains
open() with default output mode. It inherits the
functions put(), seekp(), tellp() and write() from
ofstream.
3. stream: It support for simultaneously input and
output operations. Contains open() with default input
mode. It inherits all the functions from iostream.
4. filebug: It sets the file buffers to read and write. It
contains close() and open() member functions.
5. fstreambase: This is the base class of fstream,
ifstream and ofstream classes. Therefore, it provides
operations common to these file streams. It also

3. Data files

The data file are the file that store data


belonging to a specific application.

Data files
Stored in two ways

A text file stores information in


ASCII characters. Each lines of
text is terminated, with a special
character known as EOL (End Of
Line) character.
A binary file stores information in
same format in which the
information is held in memory.
There is no termination for a line.
Files are by default considered
and treated as text file.

4. Opening And Closing


Files

It can be achieved by two ways:


1) Using the constructor function of the stream class.
2) Using the function open ( ).

Opening File using constructors


This method is preferred when single file is used
with stream.
The constructor of stream classes (ifstream,
ofstream or fstream) are used to initialize file
stream objects with the filenames passed to them.

For example:

ifstream input_file (DateFile);


File to be open

File stream of input


type
Object of input
file stream

To read from this file


Using getform operator (>>)
char burger;
input_file>>burger;
float price;
input_file>> price;
similarly

ofstream output_file (DateFile);


/* this would create a output stream object name

output_file and attach the file DataFile with it.

*/

Using the function open ( ).


Required to open more than one file.
It may be worked simultaneously but it require
separate stream for each file.
It may be sequential (one by one) by open a
single stream with each file in turn.
Note that the first file is closed before opening
second file.

File Modes
It describes how a file is to be used : to write, read etc.
Used as a second argument.
Stream_object.open (filename, (filemode) );

File mode constants


constants

Meaning

Stream type

ios::in

open file for reading only

ifstream

ios::out

open file for writing only

ofstream

ios::ate

Go to end of file on opening

ofstream
ifstream

ios::app

Append to end of file.

ofstream

ios::trunc

delete the contents of the file if it

ofstream

exists
ios:nocreate

open fails if the file does not exist

ofstream

ios::noreplace
ios:binary

open fails if the file already exists


Binary file

ofstream
ofstream
ifstream

Stream_object.open (filename, (filemode) );

If open ( ) is not successful, the stream objects stores Null (Zero) value.

Closing a File
Stream_object close( );

// syntax

A file is closed using the member function close(), as follows:


Example:

ifstream obj;
---------------------

obj.close();
For instance, if a file master is connected with an ofstream object fout, its
connection with the stream fout can be terminated as following:
fout. close( );
Close ( ) flushes the buffer before terminating the connection of the file
with stream.

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 (i.e., on the Unix file system):
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";
exit(1); // requires <stdlib.h>}

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 generally can't back up.
7: When done with the file:
in_stream.close();
out_stream.close();

fig (a) File Dos shell


option
After writing the program.

Those are the contents of


file created through
program

Fig (b) Viewing a data file created through a program

The default file behaviour type stream (ios::out file


mode)
To change the default behaviour ,then it by
specifying any of the following file mode with
open ( ) function.
File mode

behaviour

ios:: app

To retain the previous contents of the file.

ios:: ate

To place file pointer at the end of the file.

ios:: trunc

It cause to the existing file to be


truncated.

ios::nocreate

Ensures that no file is created.

ios::noreplace

A new file gets created, if already exists,


the open () fails.

a) The get( ), getline ( ) and put( ) Functions


The get( ) will read a byte of data and put( ) will write a byte of data.
istream & get(char & ch);
ostream & put (char ch):

these functions are designed for handling a


single character at a time

getline ( ) Functions
Another member function that perform input is getline ( ) whose prototype is
istream & getline (char * buf, int num, char delim = \n);
This func. Is virtually identical to get (buf, num, delim ) version of get( ).
getline() also reads character s from input stream and put them in the array
pointed to by buf until either num characters have been read, or the character
specified by delim is encounter. The default value of delim is newline character.

b) The read ( ) and write ( ) Functions


read() & write() functions: these functions are designed to write and read blocks of
binary data.
syntax:

obj.write((char*)&var, sizeof(var));
obj.read((char*)&var, sizeof(var));

Here var is an variable of either class or structure.


The data written to a file using write( ) can only be read accurately using
read().
The istream class contains input functions such as
get( )
getine( )
read( )
The ostream class contains functions such as
Put( )
write( )

It can detect when end of the file is reached by using the member
function eof ( ) which has the prototype
int eof( );
It returns non zero when the end of the file has been reached, otherwise
it resume to zero.
ifstream fin;
fin.open (Master , ios::in | ios :: binary);
while (! fin.eof ( ))
//as long as eof( ) is zero
{
// that is the files end not reached
:
//process the file
:
} if (fin.eof())
// if nonzero
cout<<End of the file reached ! \n;
It uses eof( ) with the stream object to check for the files end.

To detect the end of the file, without using EOF


( ), have to check whether the stream object

9. File pionter and random access:


Each file has two associated pointers known as the
file pointers.
1. input pointer or get pointer
2. output pointer or put pointer.
We can use these pointers to move through the files
while reading or writing.
When we open a file for reading only, the input
pointer is automatically set at the beginning so
that we can read the file from the start.
When we open a file in writing mode only, the
existing contents are deleted and the output
pointer is set at the beginning. This enable us to
write to the file from the start.

FUNCTIONS FOR MANIPULATION OF FILE POINTERS:

The file stream classes support the following


functions to move a file pointer to any other
desired position inside the file.
1. seekg(): Moves get pointer (input) to a
specified location.
2. seekp(): Moves put pointer (output) to a
specified location.
3. tellg(): Gives the current position of the get
pointer.
4. tellp(): Gives the current position of the put
pointer.
The seekg & tellg functions are associated

NOTES REGARDING SEEK FUNCTIONS:


seekg() and seekp() can also be used with two
arguments as follows:
seekg(offset, refposition):
seekp(offset, refposition);
The parameter offset represents the number of
bytes the file pointer is to be moved from the
location
specified
by
the
parameter
refposition. The refposition takes one of the
following three constants defined in the ios
class:
(i) ios::beg start of the file
(ii) ios::cur current position of the pointer
(iii)ios::end end of the file

File Pointer offset call


Seek call

Action

fout.seekg(0,ios::beg);

go to start

fout.seekg(0,ios::cur);

stay at the current position

fout.seekg(0,ios::end);

go to end of file

fout.seekg(m,ios::beg);

move to (m+1)th byte in


the file.

fout.seekg(m,ios::cur);

go forward by m byte from


the current position

fout.seekg(-m,ios::cur);
bytes from

go backward by m
the current position

fout.seekg(-m,ios::end);
bytes

go backward by m
from the end

10. Basic operations on binary files

1. Searching

2. Appending Data

3.Insert Data In Stored File


4.Deleting a Record
5.Modifying Data

11. Error Handling During File


I/O
The following errors creep in during file operations.
A file being opened for reading might not exist.
ii) A file name used for a new file may already exist.
iii) When invalid operation performed.
iv) When not enough space in the disk for storing
data.
i)

Functions

Meanings

int bad ( )

Returns non-zero (true ) value if an invalid operation


is attempted.

int eof ( )

Returns non-zero if eof is encountered while reading.

int fail ( )

Returns non-zero when an input/ output operation


has failed.

int good ( )

Returns non zero if no error has occurred.

Clear ( )

Resets the error state so that further operations can


be attempted.

A file is a bunch of bytes stored on some storage device.


C ++ s fstream predefines a set of handling file I/O.
The fstream class ties a file to the output stream for output; and fstream
class ties the files to the stream for both input and output.
The classes defined inside fstream.h derive for classes under iostream.h.
A file can be opened in two ways 1) using the constructor function of the
stream class ( this method is useful when a single file is used with a stream ),
and 2) using the function open( ),( this method is useful for managing
multiple files with a same stream).
A file mode describes how a file to be used: read it , write to it, append it
and so on. Different file modes are ios::in, ios::out, ios::ate, ios::app,
ios::trunc, ios::nocreate, ios::noreplace, ios::binary.
A file can be closed i.e., its connecting with the stream is terminate using
functions close( ).

In order to process files, follow this steps:


1)determine the type of link.
2)declare a stream accordingly.
3)link file with the stream.
4)process are required, and
5)de-link the file with stream.
The functions get ( ) ,put( ) read and write the
data respectively, one byte at a time.
The get( ) doesn't extract the delimiter
character from the input stream while the
getline( ) reads and remove the delimiter
character from the input stream.

The blocks of binary data can also be read from


and written to using read ( ) and write ( ) functions
respectively.
The functions seekg( ), and seekp( ). Let you
manipulate get-pointer and put-pointer in the file.
The functions tellg( ) and tellp( ) written the
position get-pointer and put-pointer in the file
respectively stream.
The function eof ( ) determines the end of file by
returning true for end of file otherwise by returning
false.
.

C++ also provide certain error functions hat


insure smooth working of program these functions

END OF SLIDE SHOW


Press Esc to Exit !!!!!!!!!!!!

Have a Nice day

(@_@)

Regarding :
bishnu

You might also like