SlideShare una empresa de Scribd logo
1 de 56
Data which are permanently stored in a computer are called Files.
Word Processor creates document files. Database programs create
files of information. Compiler read source file and generate executable
files. A file itself is a bunch of bytes stored on some storage devices like
Hard Disk, DVDs etc.
A file, at its lowest level is a sequence or stream of bytes. At this level,
the notation of data type is absent. In C++, file input/output facilities are
implemented through a component header file named ‘fstream.h’.
A stream is a sequence of bytes. In other words, a stream is a name given to a flow of
data. Different streams are used to represent different kind of data flow. The ‘fstream
library predefines operations for reading and writing Data to and from a Data File. It
mainly consists of 3 classes that will perform file input and output. These are
‘ifstream’, ‘ofstream’ and ‘fstream’. ‘ifstream’ class ties a file with input file stream,
‘ofstream’ class ties a file with output file stream and ‘fstream’ class ties a file with
both input and output file streams. 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 received data into the file.
Data output
to file
Data input
to program
Disk File
Program
Write data to file Read data from file
output
stream
input
stream
Click Me 
ofstream
Click Me 
ifstream
Data from program
Raman, Balan, Soman
Data from File
Raman, Balan, Soman
The ‘fstream.h’ Header File. The ‘fstream library predefines a set of operations
for read and write operations with Data Files. It mainly defines 3 classes that will
perform file input and output. These are ‘ifstream’, ‘ofstream’ and ‘fstream’.
‘ifstream’ class ties a file with input file stream, ‘ofstream’ class ties a file with output
file stream and ‘fstream’ class ties a file with both input and output file streams.
ios
iostream
istream ostream
ifstream ofstream
streambuf
filebuf
fstreambase
fstream
strstreambuf
HOLDS-A Relationship.
To get help of any class,
type class name and
press Ctrl+F1
Functions of File Stream Classes.
Class Functions
filebuf It provides low level facilities. We can’t use filebuf directly. It
is part of other file classes.It sets the file buffers to read and
write. It contains open() and close() member function.
fstreambase This is the base class for fstream, ifstream and ofstream
classes. Therefore, it provides operations common to these
file streams. It also contains open() and close() functions.
Ifstream Being an input file stream class, It provides input operations
for file. It inherits the functions get(), getline(), read() and
other seekg() and tellg() functions supporting random acces.
ofstream It provides output operations. It inherits put() and write()
functions along with seekp() and tellp() functions supporting
random acces.
fstream It is a input as well as output file stream class. It provides
support for simultaneous input and output operations. It
inherits all the functions from istream and ostream classes
through iostream class defined inside iostream.h file.
The data files are the files that stores data pertaining to a specific application, for
latter use. The data files can be stored in two ways. (i) Text Files. (ii) Binary Files.
A text file stores information in ASCII characters. In text file each line of text is
terminated with a special character known as End Of Line (EOL). In text files some
internal translations take place when this EOL character is read or written.
You can think of text files as sequence of bytes broken into subsequence with a
special EOL character. Processing of this character leads to some internal
translations taking place. It is not in the case of Binary Files.
A binary file is just a file that contains information in the same format in which the
information is held in memory there is no delimiter for a line. Also no translations
occur in binary files. As a result, a binary files are faster and easier for a program to
read and write than text files. As long as the file does not to read by people or need
to be ported to a different type of system. Binary files are the best way to store
program information.
When you work with files in C++, unless you specify, files are by default considered
and treated as text file.
OPENING AND CLOSING FILES. To open a File, first declare an object, that
satisfies our need. Write data into a file, use an object of class ‘ofstream’. Read data
from a file use ‘ifstream’. For both read and write operation, use an object of class
‘fstream’. After that, you must specify the name of file you want to manipulate. This
process is called ‘File Open”. Opening of a file is done in two ways.
(i). Using the constructor function of the stream class.
(ii). Using the function open().
Declaration of ifstream
Object.
(For Read Data From File.)
Open using Constructor.
ifstream a = “ABC.TXT”;
Or
ifstream a(“ABC.TXT”);
Open using ‘open()’
ifstream a;
a.open(“ABC.TXT”);
Declaration of ofstream
Object.
(For write Data into File.)
Open using Constructor.
ofstream a = “ABC.TXT”;
Or
ofstream a(“ABC.TXT”);
Open using ‘open()’
ofstream a;
a.open(“ABC.TXT”);
Declaration of fstream
Object.
(Both Read and Write.)
Open using Constructor.
fstream a (“ABC”, Mode);
Or
fstream a(“ABC”, Mode);
Open using ‘open()’
fstream a;
a.open(“ABC.TXT”, Mode);
Data
File
Program
Read From File Write into File
I T I S O F S T
Object Performs All
Read/Write Operations.
Stream
class fstream
{
Description of member
functions like open(),
close(), getc(), put(),
read(), write() etc.
}
Declaration
of Object.
fstream a = “ABC.TXT” ABC.TXT
To close the link with the file
“ABC.TXT”, Call ‘close()’ function
in association with stream Object.
Here a.close();
Stream representing the file ABC.TXT.
To read and write data to and from a File, Simply use the << (Insertion) and >>
(Extraction) Operators, in the same way that are used with cin and cout. And except
that, instead of using cin and cout, substitute a stream that is linked to a file.
ofstream a = “PLEDGE.TXT”;
cout << “nINDIA IS MY COUNTRY ALL INDIANS ARE MY BROTHERS & SISTERS”;
a << “nINDIA IS MY COUNTRY ALL INDIANS ARE MY BROTHERS & SISTERS”;
Insert this caption into Console Output ‘cout’.
‘a’ is ofstream object, it is linked to the file PLEDGE.TXT. Hence the caption will be
insert into the file PLEDGE.TXT instead of cout
ifstream a = “STUDENT.TXT”;
char name[20];
cin >> name;
a >> name;
Extract Name form Console input(KeyBoard).
‘a’ is ifstream object, and linked with the file
STUDENT.TXT. Hence the Name stored in
STUDENT.TXT will be extracted, and assigned in the
array name[20];
# include <iostream.h>
# include <fstream.h>
main()
{
char name[20];
int rollno;
cout << "nPlease Enter Name & Roll No ";
cin >> name >> rollno;
cout << "nThe Name stored in STUDENT.TXT is “;
cout << name << " " << rollno;
}
A simple program that will read Name & Roll No of a student and write them into a file
name “STUDENT.TXT”. After that, extract Name & Roll No from that file.
O
F
S
T
R
E
A
M
DATA FILE
STUDENT.TXT
I
F
S
T
R
E
A
M
ofstream a;
ifstream b;
ofstream a = "STUDENT.TXT"; // Click Me 
ifstream b; // Click Me 
a << “n” << name << " " << rollno; // Click Me 
a.close(); b.open("student.txt"); // Click Me 
b >> name >> rollno; // Click Me 
Anil 100
Anil 100
ofstream – Write data into File.
ifstream – Read data from File.
Write Data through object ‘a’..
Read data through object ‘b’.
The Concept of File Modes. File modes are certain constants, which are defined in the class
‘ios’. It describe how a file is to be used: to read data from it, to write to it, to append it and so
on. The constructors and open() functions of class ifstrean and ofstream have two arguments.
The first argument is the name of file to be open and the second one is File Mode. File mode is
not compulsory. If you omit it, the function will provide default File Mode. ‘ifstream’ use the
constant ios :: in and ‘ofstream’ use ios :: out as their default File Mode. The ‘fstream’ class
does not provide a default mode. Therefore one must specify ‘file mode’ explicitly. To open a
binary file, use ios :: binary along with other File Mode. To combine two or more File mode,
use bitwise ‘OR’ ( | pipe symbol) operator. The deference between ios :: ate and ios :: app is
that the ios :: app allows you to add data at the end of the file only while ios :: ate cause to
move position at the end of file when open a file, after that one can read / write data anywhere
in the file even overwrite old data also.
Stream_name object ( “File Name”, file mode);
Object.open(“File Name”, file mode);
Eg: fstream a(“ABC.TXT”, ios :: in | ios :: out);
Or
fstream a; a.open(“ABC.TXT”, ios :: in | ios :: out);
A file is closed .by disconnecting it with the stream. Its general form is
Stream_Object.close();
Eg. a.close();
Click here
to see all
other ‘ios’
constants.

Constant Meaning Stream type
ios :: in Opens file for reading. ifstream
ios :: out
Opens file for writing. this also opens the file in ios :: trunc
mode by default. This means an existing file is truncated
when opend. i.e. its previous contents are discarded.
ofstream
ios :: ate
It seeks to end of file upon opening of the file. I/O operations
can still occur anywhere whithin the file.
ofstream
ifstream
ios :: app
This cause all output to that file to be appended to the end.
This value can be used with files capable of output.
ofstream
ios :: trunc
This value causes the content of a pre-existing file to be
destroyed and truncates the file to zero length.
ofstream
ios :: nocreate
This causes the open () function to fail if the file does not
exists.
ofstream
ios :: noreplace
This cause the open() function to fail if the file already
exists. This is used when you want to create a new file at
every time.
ofstream
ios :: binary
This cause a file to be opened in binary mode. By default
files are opened in text mode. When a file is opened in text
mode various character translations may take place such as
carriage return into new line. However no such character
translation occur in files opened in binary mode.
ofstream
ifstream
STEPS TO PROCESS A FILE IN YOUR PROGRAM.
1. Determine the type of link required.
2. Declare a stream for the desired type of link.
3. Attach the desired file to the stream.
4. Now process as required.
5. Close the File link with stream.
1. Determine the type of link required. This step requires the identification of type of
link required. If the program want to get data stored in a file, first transfer the data from
File to memory. This type of link is said to be File-to-Memory link. After some
processing the data is to be sent from memory to file. This type of link is said to be
Memory-to-File link. Some situation demands both type of links, File-to-Memory and
Memory-to-File, then two way link can be created.
Predefine string ‘cin’ is an example of File-to-Memory link. Since all devices are
treated as file, keyboard is also treated as file. With ‘cin’ data comes from the file
keyboard to memory. With ‘cout’ data goes memory to the file ‘Monitor’ hence a
Memory-to-File link is established.
2. Declare a stream for the desired type of link. After determining the type of link
required, the next step is to create a stream for it. For different type of links different
stream classes are used for stream declaration. For File-to-Memory type of link
‘ifstream’ class stream is declared. For Memory-to-File type of link ‘ofstream’ class
stream is declared. For two way type of link (Both File-to-Memory and Memory-to-File)
‘fstream’ class object is declared.
Type of Link. Used for Stream Class Example
File-to-Memory
Read Data from a
File. Bring data from
file to memory for
further processing.
ifstream ifstream a;
Memory-to-File
Write Data into a File.
Send processed Data
from Memory to File.
ofstream ofstream a;
File-to-Memory
Memory-to-File
Both Read and Write
data from and to a
file. Both input and
output purpose.
fstream fstream a;
3. Attach the desired file to the stream. After declaring streams, the next step is to
link the file with the declared stream. This is done by opening the desired file. A file
can be opened in two ways. Using constructor and using open() methode.
4. Now process as required. Under this step, processing is required is performed.
5. Close the File link with stream. At this step the link between file and stream will be
closed. This is performed through close() method.
General form of constructor. Stream-Name Object (“File Name”, Mode);
General form of open() function. Object.open(“File Name”, Mode);
ifstream a = “ABC.TXT”; ifstream b(“ABC.TXT”, ios :: in);
ifstream b(“ABC.TXT”, ios :: in | ios :: binary);
ifsream b(“ABC.TXT”, ios :: in | ios :: binary | ios :: ate);
ofsream a=“ABC.TXT”; ofstream a(“ABC.TXT”, ios :: out);
ifstream a(“ABC.TXT”, ios :: in | ios :: binary);
ofstream a(“ABC.TXT”, ios :: out | ios :: binary | ios :: ate);
File Opening Modes
ios :: in  Input
ios :: out  Output
ios :: ate  At End
ios :: app  Append
ios :: trunc  Truncate
ios :: binary
ios :: nocreate
ios :: noreplace
// Read Name & Roll No of several Students and write
them into a file named “STUDENT.TXT”.
# include <iostream.h>
# include <fstream.h>
main()
{
char name[20];
int rollno;
char ans;
do
{
cout << "nnPlease Enter Name & Roll No ";
cin >> name >> rollno;
cout << "nnDo You Want To Continue (Y/N) ?. ";
cin >> ans;
}while( ans=='y' || ans == 'Y');
a.close();
}
a << "n" << name << " " << rollno; // Click Me
Repeat this
while ans = Yes

O
F
S
T
R
E
A
M
DATA FILE
STUD.TXT
Anil 100
ofstream a("STUD.TXT“, ios :: out); // Click Me 
//Read Name & Roll No from the file “STUDENT.TXT”.
# include <iostream.h>
# include <fstream.h>
main()
{
char name[20];
int roll;
ifstream a(“STUD.TXT”, ios :: in);
while( !a.eof() )
{
a >> name >> roll;
cout << "nName “ << name << “Roll No “ << roll;
}
a.close();
}
I
F
S
T
R
E
A
M
Anil 100
Babu 101
Sunil 102
DATA FILE
STUDENT.TXT
Click Me 
eof() Function will returns non-zero(True Value) if
end-of-file is encountered while reading otherwise
returns zero(False Value).
General Form is : Object.eof()
Eg. a.eof()  Check whether the EOF is reached on
the associated file. (Here “STUDENT.TXT”)
EOF is a
constant
indicating that
end-of-file has
been reached
on a file.
Sunil 102
Repeat while Not
EOF
Returns EOF

Anil 100
Babu 101
Repeat this
while not EOF

Detecting EOF. You can detect when the end of file has been reached or not by
using the member function eof(). It will returns non-zero if EOF is encountered
otherwise return zero.
ifstream ifs = “STUD.DAT”  Opens STUD.DAT through the input file stream ‘ifs’.
if ( ! ifs )  When the file can’t open ifstream object ‘ifs’ becomes zero.
cout << “File Can’t Open”;
else
cout << “File Opened”;
while ( ! ifs.eof() )
{
}
Read Data While Not EOF.
while ( ifs )
{
}
The Stream Object always denote the status of the Stream.. Status value zero
indicates that the stream is not ready for read or write operation. Non-zero value
indicates that the stream is ready.
Read data While status is Non-Zero
Repeat this
while not EOF

Repeat this
While status
Is Non-Zero.

# include <iostream.h>
# include <fstream.h>
main()
{
char name[20];
int rollno, m1, m2, m3, tot;
char ans;
ofstream ofs(“STUDENT.DAT”, ios :: out);
ifstream ifs;
do
{
cout << "nnPlease Enter Name & Roll No ";
cin >> name >> rollno;
cout << "nnPlease Enter 3 Marks ";
cin >> m1 >> m2 >> m3;
ofs << “n” << name << “ “ << rollno << “ “ << m1
<< “ “ << m2 << “ “ << m3 << “ “ << m1+m2+m3;
cout << "nDo You Want To Continue (Y/N) ?. ";
cin >> ans;
}while( ans=='y' || ans == 'Y');
ofs.close();
Read Name,Roll No, marks in 3 subjects of several Students and write them into a file
named ‘STUDENT.DAT’
Ifs.open(“STUDENT.DAT”, ios :: in);
while ( ! ifs.eof())
{
ifs >> name >> rollno >> m1 >> m2 >> m3
cout << “n” << name << “ “ << rollno << “ “ <<
m1 << “ “ << m2 << “ “ << m3 << “ “ <<
m1+m2+m3;
} // loop ends.
} // end of main()
Anil 100 34 26 40 100
Babu 101 28 32 30 90
Sunil 102 37 23 25 85
DATA FILE
STUDENT.DAT
Anil 100 34 26 40 100
Click Me 
Babu 101 28 32 30 90Sunil 102 37 23 25 85
EOF
Read each Record from
“STUDENT.DAT”.
Repeat this
Click Me 
Repeat this
while not EOF

Returns EOF

Anil 100 34 26 40 100
Babu 101 28 32 30 90
Sunil 102 37 23 25 85
// Store details of some items into a file named “ITEM.DAT”
# include <iostream.h>
# include <fstream.h>
main()
{
char name[20], ans; int code, qty; float price;
ofstream ofs("ITEM.DAT", ios :: out);
ifstream ifs;
ofs.close();
ifs.open("ITEM.DAT", ios :: in);
}
do
{
cout << "nnPlease Enter Item Name, code, qty and Price ";
cin >> name >> code >> qty >> price;
ofs << "n" << name << " " << code << " " << qty << " " << price;
cout << "nnDo You Want to Continue (Y/N) ?. ";
cin >> ans;
}while(ans == 'y' || ans == 'Y');
while( ! ifs.eof() )
{
ifs >> name >> code >> qty >> price;
cout << "n" << name << " " << code << " " << qty << " " << price;
}
Pencil 100 25 5.25
Pen 101 50 7.50
Ink 102 35 12.75
DATA FILE
ITEM.DAT
EOF
O
F
S
T
R
E
A
M
I
F
S
T
R
E
A
M
ofs
ifs
Click Me 
Click Me 
Pencil 100 25 5.25
Pen 101 50 7.50
Ink 102 32 12.75
Returns EOF

Repeat this
while ans = Yes

Pencil 100 25 5.25Pen 101 50 7.50Ink 102 32 12.75
# include <iostream.h>
# include <conio.h>
# include <fstream.h>
main()
{
char empname[20], desig[20], ans;
int empno;
float basic;
ofstream emp("EMPLOYEE.DAT", ios :: out);
ifstream ifs;
do
{
cout << "nnPlease Enter Name, Emp No,
Designation and Basic Pay ";
cin >> empname >> empno >> desig >> basic;
emp << "n" << empname << " " << empno <<
" " << desig << " " << basic;
cout << "nDo You Want to Continue (Y/N) ?. ";
cin >> ans;
}while(ans == 'y' || ans == 'Y');
emp.close();
ifs.open("EMPLOYEE.DAT", ios :: in);
while( ! ifs.eof() )
{
ifs >> empname >> empno >> desig
>> basic;
cout << "n" << empname << " " <<
empno << " " << desig << " " << basic;
}
getch();
}
Repeat this
while ans = Yes

Repeat this
while not EOF

# include <iostream.h>
# include <conio.h>
# include <fstream.h>
main()
{
char name[20], ans; int roll; float per;
ofstream pass("PASS.DAT", ios :: out);
ofstream fail("FAIL.DAT", ios :: out);
ifstream ifs;
do
{
cout << "nPlease Enter Item Name, Roll No and
% of Marks ";
cin >> name >> roll >> per;
cout << "nnDo You Want to Continue (Y/N) ?. ";
cin >> ans;
}while(ans == 'y' || ans == 'Y');
pass.close(); fail.close();
ifs.open("PASS.DAT", ios :: in);
while( ! ifs.eof() )
{
ifs >> name >> roll >> per;
cout << "n" << name << " " << roll
<< " " << per;
}
ifs.close();
ifs.open(“FAIL.DAT", ios :: in);
while( ! ifs.eof() )
{
ifs >> name >> roll >> per;
cout << "n" << name << " " << roll
<< " " << per;
}
ifs.close();
}
if (per>=50)
pass << "n" << name << " " << roll << " " << per;
else
fail << "n" << name << " " << roll << " " << per;
Read name, roll no and % of Marks, if % of marks >=50 then
write this record into PASS.DAT else write it in FAIL.DAT.
Raman 100 58 Balan 101 45Click Me 
Changing the Behavior of Streams.
The default behavior of ifstream is reading data from a text file. And if the file
mode is ios :: in | io :: binary then reading is performed on a binary file.
The default behavior of ofstream is ios :: out. When we use this mode, if the file
does not exists it will create a new one else it will erase all previous data. We can
change this mode by specifying any of following file mode.
To read from or write to a binary file, the file mode must contain ios :: binary in
combination with other file mode.
ios :: app
To retain previous contents of the file and to append to the end of
existing file.
Ios :: ate
Place the file pointer at the end of file but one can write data
anywhere in the file.
Ios :: trunc It causes the existing file to be truncated.
ios :: nocreate
If the file does not exist, this file mode ensure that no file is created
and hence open() fails. However, if the file exists it gets opened.
ios ::
noreplace
If the file does not exist, a new file gets created but if the file already
exist, the open() fails.
SEQUENTIAL I/O WITH FILES. Sequential read and write from and into the file is
called Sequential access. The functions get() and put() are capable of handling a
single character at a time. The function getline() lets you handle multiple characters at
a time. Another pair of function read() and write() are capable of reading and writing
block of binary data.
The Function get() will read a byte (one character) from the stream and put() will write
a byte into the stream. The general form of get() and put() is given bellow.
istream & get ( char &ch); ostream & put (char );
# include <iostream.h>
# include <conio.h>
# include <fstream.h>
main()
{
char ch=0;
ofstream ofs="PLEDGE.TXT";
ifstream ifs;
cout << "nEnter a National Pledge ";
while( ch != 27) // ASCII of Escape is 27
{
ch = getche();
ofs.put(ch);
}
ofs.close();
ifs.open("PLEDGE.TXT");
cout << "nnnThe Content of
PLEDGE.TXT isnn";
while ( ! ifs.eof() )
{
ifs.get(ch);
cout.put(ch);
}
cout << "nnnPress any Key.....";
getch();
}
Getting Each Character
and put it in PLEDGE,TXT
Repeat this
while ch != ESC

// Read National Pledge & write it in a File PLEDGE.TXT.
Getting Each Character from
File and put it in MONITORRead each Character
while not EOF

The other forms of get() Function.
istream & get ( char *buf, int num, char delim = ‘n’); Reads more characters into a
character array named ‘buf’ until either ‘num’ characters have been read or the
character specified by delim has been encountered. The array will be NULL
terminated by get(). If no delimiter character is specified, by default a new line
character (’n’) acts as a delimiter.
int get(); It will read a single character from the stream.
# include <iostream.h>
# include <conio.h>
main()
{
char name[30];
cout << "nEnter Your Full Name ";
cin.get(name, 30, '.‘ );
cout << "nnHai " << name;
getch();
}
OUTPUT
Enter Your Full Name Anil Kumar P.
Hai Anil Kumar P
# include <iostream.h>
# include <conio.h>
main()
{
char name[30];
cout << "nEnter Your Full Name ";
cin >> name;
cout << "nnHai " << name;
getch();
}
OUTPUT
Enter Your Full Name Anil Kumar P.
Hai Anil
Read either 30
Characters or the
‘full stop’ has been
encountered.
Read a single word
only.
See Difference
Another Prototype of getline() Function. get(char *buf, int num, char delim). And
getline ( char * buf, int num, char delim = ‘n’); are same. getline() will read several
characters from input stream and put them in the array named buf until either num
character have been read or the character specified by delim is encountered. The
difference between get(char *buf, int num, char delim) and getline(char *buf, int num,
char delim) is that getline() reads and removes the delimiter character from the input
stream if it is encoutered which is not done by get(char *buf, int num, char delim)
function.
# include <iostream.h>
# include <conio.h>
main()
{
char name[30]; int age;
cout << "nEnter Your Full Name";
cin.get ( name, 30, ’.’ );
cout << “nnEnter Age “; cin >> age;
cout << name << “ Your Age is “ << age;
getch();
}
OUTPUT
Enter Your Full Name Anil Kumar P.
Enter Age
Name Anil Kumar P Your Age -22827
# include <iostream.h>
# include <conio.h>
main()
{
char name[30]; int age;
cout << "nEnter Your Full Name";
cin.getline ( name, 30, ’.’ );
cout << “nnEnter Age “; cin >> age;
cout << name << “ Your Age is “ << age;
getch();
}
OUTPUT
Enter Your Full Name Anil Kumar P.
Enter Age 28
Name Anil Kumar P Your Age 28
Age will not read.
Because of Delimiter
character is present
in input stream.
The read () and write () functions.
istream & read (char *buf, int size); This function will read a block of binary data
from the input stream and put them in the buffer (Memory) named ‘buf. The size
of buffer is mentioned by an integer value ‘size’. The address of the variable must
be type cast to char *.
ostream & write (char * buf, int size); This function will write a block of binary data
into the output stream and put them in the buffer (Memory) named ‘buf. The size
of buffer is mentioned by an integer value ‘size’. The address of the variable must
be type cast to char *.
# include <iostream.h>
# include <fstream.h>
main()
{
char name[20], ans; int age;
ofstream ofs = "STUDENT.DAT";
ifstream ifs;
do
{
cout << "nEnter Name & Age ";
cin >> name >> age;
ofs.write( name, 20); ofs.write( (char *) &age, 2);
cout << "nDo You Want to Continue (Y/N) ?. ";
cin >> ans;
}while(ans=='Y' || ans == 'y');
ofs.close(); ifs.open("STUDENT.DAT");
while( !ifs.eof() )
{
ifs.read( name, 20); ifs.read( (char *) &age,2);
cout << "nn" << name << ", " << age;
}
ifs.close();
}
Cast to
char *
Repeat this
while not EOF

Reading and Writing Class Objects. These functions handle all data members of an
object as a single unit, using the computer’s internal representation of data. Read() and
write() functions will read and write entire data of an object from and to memory, byte
by byte. The length of an object is obtained by ‘sizeof’ operator.
# include <iostream.h>
# include <fstream.h>
struct student
{
char name[20]; int age;
};
main()
{
student a; char ans; int age;
ofstream ofs = "STUDENT.DAT";
ifstream ifs;
do
{
cout << "nEnter Name ";
cin.getline(a.name, 20);
cout << "nEnter Age ";
cin >> a.age;
ofs.write( (char *) &a, sizeof(a));
cout << "nDo You Want to Continue (Y/N) ?. ";
cin >> ans;
cin.ignore();
}while(ans=='Y' || ans == 'y');
ofs.close();
ifs.open("STUDENT.DAT");
while( !ifs.eof() )
{
ifs.read( (char *) &a, sizeof(a));
cout << "nn" << a.name << ", " << a.age;
}
ifs.close();
}
Consider Name and Age as a single unit
of size 22 bytes, and write all these 22
bytes into the file STUDENT.DAT
Read Name and
Age as a single
unit of size 22
bytes from
STUDENT.DAT
Cast to
char *
Repeat this
while not EOF

# include <iostream.h>
# include <conio.h>
# include <fstream.h>
main()
{
bank a; char ans;
ofstream ofs = "BANK.DAT";
ifstream ifs;
do
{
cout << "nDo You Want to Continue (Y/N) ?. ";
cin >> ans;
cin.ignore();
}while(ans=='Y' || ans == 'y');
ofs.close();
ifs.open("BANK.DAT");
while( !ifs.eof() )
{
}
ifs.close();
getch();
}
class bank
{
char name[20];
int acno;
float amount;
public:
void open()
{
cout << "nEnter Name ";
cin.getline(name, 20);
cout << "nEnter A/c No & Amount. ";
cin >> acno >> amount;
}
void out()
{
cout << "n" << name << ", " << acno
<< ", " << amount;
}
};
a.open(); //Click Me
ofs.write( (char *) &a, sizeof(a)); //Click Me
ifs.read( (char *) &a, sizeof(a)); //Click Me
a.out(); //Click Me
BANK.DAT
Anil Kumar
100 10000
Anil Kumar
100
10000
Do this
while ans = Yes

Repeat this
while Not EOF

Anil Kumar
100
10000
More about Reading and Writing Class Objects. Sometimes a need arise to treat a
group of different data as a single unit. For Example a record in a file can have several
fields of different types and entire record may be required to be processed in one unit.
Read() and write() functions will read and write data in multiples of the size of the
object. It include used and unused bytes. Suppose name[20] is a character array of
size 20. And the data assigned in ‘name’ is ‘ANIL”. In this case first four byres are
used. Remaining 16 bytes are unused. When performs read() and write() all 20 bytes
will be considered.
struct Student
{
char name [20];
int rollno;
} a = { “ANIL”,100 };
A N I L 0
Used
100
Unused
char name[20] roll
DATA FILE
A N I L 0 100
B A L A C H A N D R A N 0 101
H A R I 0 102
Read() &
Write()
whole 22
bytes.
With the inclusion of unused bytes, each
records have get equal Length.
STUDENT.DAT
FILE POINTERS AND RANDOM ACCESS. Moving directly to any location is called
random access. Every file maintains two pointer called get pointer and put pointer
which tell position in the file where reading and writing will take place. Get pointer is the
position where reading of data will take place and put pointer is the position where
writing of data will take place. By using seekg(), seekp(), tellg() and tellp() functions
one can place read-write position at any place and process data at that position.
seekg() and seekp() functions will place get and put pointer at specified position.
General form of these functions are given bellow.
istream & seekg(long pos) : will place ‘get-pointer’ at the position specified by pos.
ofstream & seekp(long pos) : will place ‘put-pointer’ at the position specified by pos.
istream & seekg( long, seek_dir) will place ‘get-pointer’ at the position specified by
pos relative to seek_dir. ‘seek_dir’ is an
enumaration defined in iostream.h.
ofstream & seekp( long, seek_dir) will place ‘get-pointer’ at the position specified by
pos relative to seek_dir.
Seek_dir constants are
ios :: beg  Refers to beginning of the file.
ios :: cur  Refers to current position in the file.
ios :: end  Refers to end of the file. Some Example are given bellow
DATA FILE STUDENT.DAT
A N I L 0 100
B A L A C H A N D R A N0 101
H A R I 0 102
S U N I L 0 102
struct Student
{
char name [20];
int rollno;
} a = { “ANIL”,100 };
Beging of file Assuse that here
Is the current Position.
EOF
seekg(22, ios :: cur); moves get pointer 10 bytes back from end of the file. Click Me 
seekg(22, ios :: beg); moves get pointer 10 bytes from beginning of the file. Click Me
seekg(44, ios :: beg); moves get pointer 10 bytes from current position. Click Me
seekg(-44, ios :: end); moves get pointer 10 bytes from current position. Click Me
seekg(-22, ios :: beg); ERROR. Can’t Move back from Beginning of File. Click Me 
seekg(22, ios :: end); ERROR. Can’t Move forward from end of File. Click Me 
tellg() returns the position of get pointer in bytes. Click
tellp() returns the position of put pointer in bytes. Me
seekg(-44,ios::end); cout << “Cur Position“<< tellg(); 






Each Record
has 22 Bytes.
# include <iostream.h>
# include <conio.h>
# include <fstream.h>
main()
{
Student a;
fstream fs("STUDENT.DAT", ios :: in | ios :: out | ios :: binary);
char ans;
do
{
a.input();
fs.write( (char *) &a, sizeof(a));
cout << "nnnContinue (Y/N) ?. ";
cin >> ans;
cin.ignore();
}while(ans=='y' || ans=='Y');
fs.seekg(0);
while( ! fs.eof() )
{
fs.read( (char *) &a, sizeof(a));
a.out();
}
getch();
}
class Student
{
char name[20];
int rollno;
public:
void input()
{
cout << "nnEnter Name ";
cin.getline(name,20);
cout << "nnRoll No ";
cin >> rollno;
}
void out()
{
cout << "n" << name << " " << rollno;
}
};
Function for
inputing Data.
Open the File in Read,
Write, Binary modes.
Write all 22 bytes into the
file STUDENT.DAT.
Read from STUDENT.DAT.
Do this
while ans = Yes

Repeat this
while not EOF

# include <iostream.h>
# include <conio.h>
# include <fstream.h>
# include <ctype.h>
main()
{
Student a; ifstream ifs; char ans;
ofstream ofs("STUD.DAT", ios :: out | ios :: binary );
do
{
a.input();
ofs.write( (char *) &a, sizeof(a));
cout << "nnnDo You Want To Continue (Y/N) ?. ";
cin >> ans;
cin.ignore();
}while(toupper(ans) == 'Y');
ofs.close();
ifs.open("STUD.DAT", ios :: in | ios :: binary);
while ( ifs.read( (char *) &a, sizeof(a)) ) a.out();
}
class Student
{
char name[20], grade;
int rollno, m1, m2, m3, tot; float avg, per;
void input()
{
cout << "nEnter Name ";
cin.getline(name,20);
Cout << “nEnter Roll No “; cin >> rollno;
cout << "nnEnter 3 Marks ";
cin >> m1 >> m2 >> m3;
calculate();
}
void calculate()
{
tot = m1+m2+m3; per = (tot/300.0)*100;
if (per >=90) grade = 'A';
else if (per >=80) grade = 'B';
else if (per >=70) grade = 'C';
else if (per >=60) grade = 'D';
else if (per >=50) grade = 'E';
else grade = 'F';
}
void out()
{
clrscr(); gotoxy(10,4);
cout << "Senior School Certificate Exam";
cout<<"nName :"<<name<<"t Roll No :"<<rollno;
cout<<"nTot. Marks "<<tot<<"t% of Marks"<<per;
cout << "nnGrade : " << grade; getch();
}
};
Do this while
upper(ans) = Yes

Read Each Record while Not EOF 
Searching. The process of locating desired record in a file is called Searching.
Let us imagine a Binary file STUDENT.DAT contains following records.
struct Student
{
char name [20];
int rollno;
float per;
};
A N I L 0
STUDENTS.DAT
HARI KUMAR 100 78.00
ANIL KRISHNAN 101 69.25
SURESH BABU 102 72.50
THOMAS MATHEW 103 92.00
JACOB PAUL 104 55.80
JOHN MATHEW 105 84.00
DAVID VARGHEESE 106 59.50
Object of Student
float per;
(4 Bytes)
int rollno;
(2 Bytes)
char name[20];
(20 Bytes)
All Records have
equal size.
20 (Name) +
2(rollno) + 4
(per) = 26 Bytes.
ALGORITHAM.
1. Define a structure or class ‘STUDENT’ contains name, Roll No & % of Marks. And
relevant Member Functions. class STUDENT { …. };
2. Declare an object of above class definition. And an int variable ‘x’, which is used
to store the roll no we want to searched for ?. Declare int flag = 0; If locate given
Roll No then the flag is set to 1. STUDENT a; int x, flag = 0;
3. Declare an ‘ifstream’ object ‘ifs’ and open the file. ifstream ifs = “STUDENT.DAT”;
4. Print the caption “Which Roll No You want to searched for ?“ and input value of x.
cout << “Which Roll No You want to searched for ?“; cin >> x.
5. Repeat following steps while not EOF. while ( ! Ifs.eof() ) { read (…..)…… }
i. Read each record from the input file stream. read( (char *) &a, sizeof(a) );
ii. If its Roll No = x (Roll No to be searched) then set ‘flag = 1’ and break from
loop. if ( a.rollno == x ) { flag = 1; break; }
6. If flag == 1 then print details of Object if( flag==1) a.out(); else cout << “ Not
Found.”;
7. Else Print an Error Message “Record Not Found.”
START
END
STUDENT a;
ifstream ifs = “STUDENT.DAT”;
Int x, flag = 0;
if can’t Open
cout << “Roll No ?. “;
cin >> x;
if not EOF
Read Record from File.
if a.rollno == x flag = 1; break
if flag == 1
cout << a.name << a.rollno;
OR a.out();cout << “Not Found.”
YES
NO
YES
NO
NO
YES
TEST CASES BY CLICK
File Can’t Open. Click Me
Can’t Find. Click Me
Found Record. Click Me
Case File Can’t Open

NO YES
Case : Can’t Find

Case : Find Record.

# include <iostream.h>
# include <conio.h>
# include <fstream.h>
main()
{
Student a;
fstream fs("STUDENT.DAT", ios :: in | ios :: binary);
int roll, flag = 0;
if( !fs )
{
cout << "nFile Can't Open"; return 0;
}
cout << "nEnter Roll No "; cin >> roll;
while ( fs.read( (char *) &a, sizeof(a)) )
{
if (a.rollno == roll) { flag = 1; break; }
}
if(flag == 1)
{
cout << "nGiven Record Located ";
a.out();
}
else
{
cout << "nGiven Roll No Not Found.";
}
getch();
}
struct Student
{
char name[20];
int rollno;
void input()
{
cout << "nEnter Name ";
cin.getline(name,20);
cout << "nRoll No ";
cin >> rollno;
}
void out()
{
cout << "n" << name << " “ << rollno;
}
};
Read each record &
Compare with given roll no

TEST CASES BY CLICK
Can’t Find. Click Me
Found Record. Click Me
# include <iostream.h>
# include <conio.h>
# include <fstream.h>
# include <ctype.h>
main()
{
Student a; ifstream ifs; char ans;
ofstream ofs("STUD.DAT", ios :: app | ios :: binary );
do
{
a.input();
ofs.write( (char *) &a, sizeof(a));
cout << "nnnDo You Want To Continue (Y/N) ?. ";
cin >> ans; cin.ignore();
}while(toupper(ans) == 'Y');
ofs.close();
ifs.open("STUD.DAT", ios :: in | ios :: binary);
while ( ifs.read( (char *) &a, sizeof(a)) ) a.out();
}
class Student
{
char name[20], grade;
int rollno, m1, m2, m3, tot; float avg, per;
void input()
{
cout << "nEnter Name ";
cin.getline(name,20);
Cout << “nEnter Roll No “; cin >> rollno;
cout << "nnEnter 3 Marks ";
cin >> m1 >> m2 >> m3;
}
void calculate()
{
tot = m1+m2+m3; per = (tot/300.0)*100;
if (per >=90) grade = 'A';
else if (per >=80) grade = 'B';
else if (per >=70) grade = 'C';
else grade = ‘D';
void out()
{
cout <<"n"<< name <<“,:“ << rollno << “, “ << tot <<
“, “ << per << “, " << grade;}
};
Appends while
upper(ans) = Yes

Appending Data. To append data, Open the file with ios :: out and ios app
specifications. When opening a file in ios :: app mode, the previous records is retained
and new data gets appended to the file.
Ios :: app will add new
records at end.
Write each
record into
STUD.DAT
Read Each Record while Not EOF 

Inserting data in sorted file. To insert data in a sorted file, firstly find its
appropriate position. Then copy all records prior to this determined position to a
temporary file followed by the new record and then rest of the records.
1. Find appropriate position of the record to be inserted in the file STUD.DAT.
2. Copy the records prior to determined position to a temporary file sat TEMP.DAT.
3. Write new record to temporary file TEMP.DAT.
4. Copy rest of records from STUD.DAT to temporary file TEMP.DAT.
5. Delete the file STUD.DAT and rename file TEMP.DAT as STUDENT.DAT by
issuing the following commands.
remove(“STUD.DAT”); and (rename(“TEMP.DAT”, “STUD.DAT”);)
OR
5. Overwrite existing file STUD.DAT with records in the temporary file TEMP.DAT.
Name Roll No % of Marks
Anil Kumar 100 88.00
Hari Kumar 101 82.50
Krishna Kumar 102 77.00
Babu Paul 104 60.00
Thomas Mathew 105 55.00
Sivaraman 103 65.00
Thomas Mathew 105 55.00
Name Roll No % of Marks
Anil Kumar 100 88.00
Hari Kumar 101 82.50
Krishna Kumar 102 77.00
Babu Paul 104 60.00
Sivaraman 103 65.00
Thomas Mathew 105 55.00
Name Roll No % of Marks
Hari Kumar 101 82.50
Krishna Kumar 102 77.00
Babu Paul 104 60.00
STUDENT.DAT
Sivaraman 103 65.00
TEMP.DAT
Inserting data in sorted file. To
insert data in a sorted file, firstly find
its appropriate position. Then copy
all records prior to this determined
position to a temporary file followed
by the new record and then rest of
the records.
Show Copy 
Anil Kumar 100 88.00
Anil Kumar 100 88.00
Hari Kumar 101 82.50
Krishna Kumar 102 77.00
Sivaraman 103 65.00
Babu Paul 104 60.00
Thomas Mathew 105 55.00
Records prior to
determined position.
Records after the
determined position.
# include <iostream.h>
# include <conio.h>
# include <fstream.h>
# include <ctype.h>
# include <stdio.h>
class Student
{
char name[20];
public: int roll;
void input()
{
cout << "nEnter Name "; cin.getline(name,20);
cout << "nnEnter Roll NO "; cin >> roll;
};
void out()
{
cout << "nn" << name << ", " << roll;
}
};
main()
{
Student s, ns; char ans; ifstream b;
ofstream a("STUD.DAT", ios :: app |
ios :: binary);
ofstream t("TMP.DAT", ios :: out | ios :: binary);
do
{
s.input(); a.write( (char *) &s, sizeof(s));
cout << "nConinue (Y/N) ?. ";
cin >> ans; cin.ignore();
}while(toupper(ans)=='Y');
a.close();
b.open("STUD.DAT", ios :: in | ios :: binary);
cout << "nEnter new record "; ns.input();
while( b.read( (char*) &s, sizeof(s)) &&
s.roll <= ns.roll)
{ t.write( (char*) &s, sizeof(s)); }
t.write( (char*) &ns, sizeof(ns));
if ( !b.eof() )
do {
t.write( (char*) &s, sizeof(s));
}while( b.read( (char*) &s, sizeof(s)) );
b.close(); t.close();
remove("STUD.DAT");
rename("TMP.DAT", "STUD.DAT");
b.open("STUD.DAT", ios :: in | ios :: binary);
while ( b.read( (char*) &s, sizeof(s)) )
s.out();
getch();
}
To Delete a record, the following operations are carried out.
Determine the position of the record to be deleted.
Copy all records other than the record to be deleted to a
temporary file say TEMP.DAT
Do not copy the record to be deleted to temporary file.
Copy rest of records to temporary file.
Delete original file and rename TEMP.DAT as the name of
original file.
TO DELETE A RECORD, COPY ALL RECORDS OTHER
THAN THE RECORDS TO BE DELETE INTO A
TEMPORARY FILE TEMP.DAT.
Deleting a Record.
Thomas Mathew 105 55.00
Name Roll No % of Marks
Anil Kumar 100 88.00
Hari Kumar 101 82.50
Babu Paul 104 60.00
TEMP.DAT
Anil Kumar 100 88.00
Hari Kumar 101 82.50
Thomas Mathew 105 55.00
Name Roll No % of Marks
Anil Kumar 100 88.00
Hari Kumar 101 82.50
Krishna Kumar 102 77.00
Babu Paul 104 60.00
STUDENT.DAT
All Records Other Than
The Records To Be Delete
Are Copied Into A
Temporary File Temp.Dat.
Record to be Delete.
Show Copy 
YES Shall It Delete ?
NO
Don’t Write
Anil Kumar 100 88.00
Hari Kumar 101 82.50
Krishna Kumar 102 77.00
Babu Paul 104 60.00
Thomas Mathew 105 55.00
# include <iostream.h>
# include <conio.h>
# include <fstream.h>
# include <ctype.h>
# include <stdio.h>
main()
{
Student s; char ans; int del_rol;
ofstream a("STUD.DAT", ios::app | ios::binary);
ofstream t("TEMP.DAT", ios::out | ios::binary);
ifstream b;
do
{
s.input();
a.write( (char *) &s, sizeof(s));
cout << "nnConinue (Y/N) ?. ";
cin >> ans; cin.ignore();
}while(toupper(ans)=='Y');
a.close();
b.open("STUD.DAT", ios :: in | ios :: binary);
cout << "nEnter Roll No You Want to Delete ";
cin >> del_rol;
while( b.read( (char*) &s, sizeof(s)) )
{
if (s.roll != del_rol)
t.write( (char*) &s, sizeof(s));
}
b.close(); t.close();
remove("STUD.DAT");
rename("TEMP.DAT", "STUD.DAT");
b.open("STUD.DAT", ios :: in | ios :: binary);
while ( b.read( (char*) &s, sizeof(s)) )
s.out();
getch();
}
class Student
{
char name[20];
public:
int roll;
void input()
{
cout << "nnEnter Name ";
cin.getline(name,20);
cout << "nnEnter Roll NO "; cin >> roll;
};
void out()
{
cout << "nn" << name << ", " << roll;
}
};
Copy all records
except one to TEMP

Add records
while uppor(ans) = Y

Modifying Data. To modify a record the file is opened in I/O (both read and write)
modes and locate the record we want to modify. It is done by read each record from
file and compare its ‘key field’ (Here Roll no) with given roll no. After locating the
required record, it was modified in memory. Finally the file pointer is once again
placed at the beginning of this record then record is rewritten.
Algoritham.
Define Class STUDENT and Declare an object ‘a’ of STUDENT. STUDENT a;
Declare ‘int rol’ to store roll no of the record we want to edit.
Declare ‘fstream fs(“STUD.DAT”, ios :: in | ios :: out | ios :: ate | ios binary) to read and
write records to and from the file STUD.DAT.
Ask Roll No we want to edit. cout << “Roll NO ?. “; cin >> rol;
Repeat following while not EOF. while ( !fs.eof())
Read each record from the file. fs.read( (char*) &a, sizeof(a));
If it is the record we want to edit then Input New Data, move ‘put pointer’ at the
beginning of the record and write.
if (a.roll == rol )
{
a.input(); fs.seekp(-1*sizeof(a), ios :: cur); fs.write( “char *) &a, sizeof(a) );
}
Read each Record from File.
fs.read( (char *) &a, sizeof(a));
If it’s Roll No == Given Roll No
if (a.roll == edit_roll)
Read Roll No to be EDIT.
cout << “Enter Roll No “; cin >> edit_roll;
Move ‘get pointer’ to beginning of the file.
fs.seekg(0, ios :: beg);
Input new Details.
a.input();
Move ‘put-pointer’ to beginning of record.
a.seekp(--22, ios :: cur);
Write modified record.
fs.write ( (char *) &a, sizeof(a));
If Not EOF ( while ( !fs.eof() ) )
Yes
No
If Not EOF On EOF
STOP
Can’t Find. Click Me
Found Record.
Click Me

Thomas Mathew 104 55.00
Name Roll No % of Marks
Anil Kumar 100 88.00
Hari Kumar 101 82.50
Kirshan kemar 103 60.00
TEMP.DAT
Anil Kumar 100 88.00
Hari Kumar 101 82.50
fstream fs( “STUD.DAT”, ios :: in | ios :: out | ios :: ate | ios :: binary);
Student a; int edit_roll;
cout << “Enter Roll NO “; cin >> edit_roll;
fs.seekg(0, ios :: beg);
while ( fs.read( (char *) &a, sizeof(a) )
{
if(a.roll == edit_roll)
{
a.input();
fs.seekp(-22, ios :: cur);
fs.write( (char *) &a, sizeof(a));
}
}
void Student :: input()
{
cout << “nEnter Name & Roll No “;
cin.getline(a.name, 20); cin >> a.roll;
}
Show Editing 

After reading
the record,
‘get pointer’ is
positioned at
this point.
‘put pointer’
Record to be edited
Edit_roll = 103

KRISHNA KUMAR 103 60.00
# include <iostream.h>
# include <conio.h>
# include <fstream.h>
# include <ctype.h>
# include <stdio.h>
main()
{
Student s;
char ans; int edit_rol;
fstream a("STUDENT.DAT", ios :: in | ios :: out | ios :: ate | ios :: binary);
do
{
s.input();
a.write( (char *) &s, sizeof(s));
cout << "nConinue (Y/N) ?. ";
cin >> ans; cin.ignore();
}while(toupper(ans)=='Y');
cout << "nEnter Roll No You Want to Edit ?.";
cin >> edit_rol;
a.clear(); a.seekg(0, ios :: beg);
while( a.read( (char*) &s, sizeof(s)) )
{
if (s.roll == edit_rol)
{
cout << "nCurrent DETAILS "; s.out();
cout << "nPlease Enter New DETAILS";
s.input(); a.seekp( -22, ios :: cur);
a.write( (char*) &s, sizeof(s));
}
}
a.clear(); a.seekg(0, ios :: beg);
while( a.read( (char*) &s, sizeof(s)) )
s.out();
a.close(); }
class Student
{
char name[20];
public:
int roll;
void input()
{
cin.seekg(0, ios :: beg);
cout << "nEnter Name "; cin.getline(name,20);
cout << "nEnter Roll NO "; cin >> roll;
};
void out()
{
cout << "nn" << name << ", " << roll;
}
};
Move put_pointer to the beginning
of the Record.
ERROR HANDLING DURING FILE I/O. Some times during file operations, error may
also creep in. To check for errors and to ensure smooth processing, C++ file stream
inherit ‘stream-state’ members from the ios class that stores current status of a file.
enum io_state
{
goodbit = 0x00, // no bit set: all is ok
eofbit = 0x01, // at end of file
failbit = 0x02, // last I/O operation failed
badbit = 0x04, // invalid operation attempted
hardfail = 0x80 // unrecoverable error
};
Name Value
eofbit 1 when end of file else 0
failbit 1 when a non-fatal error
has occurred else 0.
badbit 1 when a fatal error has
occurred else 0.
goodbit 0 value.
Function Meaning
int bad() Returns non zero if an invalid operation is attempted or any
unrecoverable error has occurred.
int eof() Returns non-zero if EOF is encountered otherwise zero
int fail() Returns non-zero when an operation has failed.
int good() Returns non zero if no error has occurred else return 0.
clear() Reset the error state so that further operations can be attempted.
Thomas Mathew 105 55.00
Name Roll No % of Marks
Anil Kumar 100 88.00
Hari Kumar 101 82.50
Babu Paul 104 60.00
TEMP.DAT
Anil Kumar 100 88.00
Hari Kumar 101 82.50
Thomas Mathew 105 55.00
Name Roll No % of Marks
Anil Kumar 100 88.00
Hari Kumar 101 82.50
Krishna Kumar 102 77.00
Babu Paul 104 60.00
STUDENT.DAT
Anil Kumar 100 88.00
Hari Kumar 101 82.50
Krishna Kumar 102 77.00
Babu Paul 104 60.00
Thomas Mathew 105 55.00
All Records Other Than
The Records To Be Delete
Are Copied Into A
Temporary File Temp.Dat.
Record to be Delete.
Show Copy 
Shall It Delete ?
A file is a bunch of bytes stored on some storage device.
C++’s fstream library predefines a set of operations for handling file I/O.
The ifstream class ties a file to the input stream for input.
The ofstream class ties a file to the output stream for output.
The fstream class ties a file to the stream for both input and output.
The classes defined inside fstream.h derive from classes under iostream.h
A file can be opened in two ways (i) using the constructor function of the stream class.
(ii) Using the function open().
A file mode describes how a file is to be used, read it, write to it, append it and so on.
Different file modes are ios::in, ios::out, ios::app, ios::ate, ios::trunc, ios::nocreate,
ios::noreplace.
A file can be closed i.e its connection with the stream is terminated using function
close().
In order to process files, follow these steps (i) determine the type of link. (ii) Declare a
stream accordingly. (iii) Link file with the stream, (iv) Process as required. (v) Delink the
file with the stream.
The function get(), put() read and write data respectively one byte at a time.
The get() and getline() read characters into character array pointed to by buf until
either num characters have been read or the delimiter character is encountered.
The get() does not extract the delimiter character from the input stream while the
getline reads and removes the delimiter character from the input stream.
A block 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() return the position of get-pointer and put-pointer
respectively in a file stream.
The function eof() determines the end of file by returning true for end of file
otherwise by returning false.
C++ also provides certain error handling functions that ensure smooth working of
the program. These functions are eof(), bad(), fail(), and good().
LET US REVISE


65526
65525
65524
65523
65522
65521
65520
65519
65518
65517
65516
65515
65514
65513
65512
65511
65510
65509
p 65524
a=15, b


Show Order 
6
5
5
0
0
6
5
5
0
1
6
5
5
0
2
6
5
5
0
3
6
5
5
0
4
6
5
5
0
5
6
5
5
0
6
6
5
5
0
7
6
5
5
0
8
6
5
5
0
9
6
5
5
1
0
6
5
5
1
1
6
5
5
1
2
6
5
5
1
3
6
5
5
1
4
6
5
5
1
5
6
5
5
1
6
6
5
5
1
7
6
5
5
1
8
6
5
5
1
9
6
5
5
2
0
6
5
5
2
1
6
5
5
2
2
6
5
5
2
3
6
5
5
2
4
6
5
5
2
5
6
5
5
2
6
6
5
5
2
7


p 65524
p
4
0
1
5
4
0
1
9
4
0
2
2
FREE A 3.14
10
8
7
9
4012
a
Click Me 
c


c
6


anil
6


Click Me

Show Order 
6
5
5
0
0
6
5
5
0
1
6
5
5
0
2
6
5
5
0
3
6
5
5
0
4
6
5
5
0
5
6
5
5
0
6
6
5
5
0
7
6
5
5
0
8
6
5
5
0
9
6
5
5
1
0
6
5
5
1
1
6
5
5
1
2
6
5
5
1
3
6
5
5
1
4
6
5
5
1
5
6
5
5
1
6
6
5
5
1
7
6
5
5
1
8
6
5
5
1
9
6
5
5
2
0
6
5
5
2
1
6
5
5
2
2
6
5
5
2
3
6
5
5
2
4
6
5
5
2
5
6
5
5
2
6
6
5
5
2
7
Modifying Data. To modify a record the file is opened in I/O (both read and write)
modes and locate the record we want to modify. It is done by read each record from
file and compare its ‘key field’ (Here Roll no) with given roll no. After locating the
required record, it was modified in memory. Finally the file pointer is once again
placed at the beginning of this record then record is rewritten.
Thomas Mathew 105 55.00
Name Roll No % of Marks
Anil Kumar 100 88.00
Hari Kumar 101 82.50
Babu Paul 104 60.00
TEMP.DAT
Anil Kumar 100 88.00
Hari Kumar 101 82.50
Thomas Mathew 104 55.00
Name Roll No % of Marks
Anil Kumar 100 88.00
Hari Kumar 101 82.50
Kirshan kemar 103 60.00
TEMP.DAT
Anil Kumar 100 88.00
Hari Kumar 101 82.50
Edit the record who’s
roll no = 103.

Más contenido relacionado

La actualidad más candente

basics of file handling
basics of file handlingbasics of file handling
basics of file handling
pinkpreet_kaur
 
Files in c++ ppt
Files in c++ pptFiles in c++ ppt
Files in c++ ppt
Kumar
 

La actualidad más candente (19)

File in cpp 2016
File in cpp 2016 File in cpp 2016
File in cpp 2016
 
File Handling In C++
File Handling In C++File Handling In C++
File Handling In C++
 
C++ Files and Streams
C++ Files and Streams C++ Files and Streams
C++ Files and Streams
 
File handling in c++
File handling in c++File handling in c++
File handling in c++
 
File Handling
File HandlingFile Handling
File Handling
 
File Handling In C++(OOPs))
File Handling In C++(OOPs))File Handling In C++(OOPs))
File Handling In C++(OOPs))
 
Filehandling
FilehandlingFilehandling
Filehandling
 
data file handling
data file handlingdata file handling
data file handling
 
File handling in_c
File handling in_cFile handling in_c
File handling in_c
 
Filehandlinging cp2
Filehandlinging cp2Filehandlinging cp2
Filehandlinging cp2
 
Data file handling in python introduction,opening & closing files
Data file handling in python introduction,opening & closing filesData file handling in python introduction,opening & closing files
Data file handling in python introduction,opening & closing files
 
basics of file handling
basics of file handlingbasics of file handling
basics of file handling
 
File handling in C++
File handling in C++File handling in C++
File handling in C++
 
Data file handling in python reading & writing methods
Data file handling in python reading & writing methodsData file handling in python reading & writing methods
Data file handling in python reading & writing methods
 
Files in c++ ppt
Files in c++ pptFiles in c++ ppt
Files in c++ ppt
 
Stream classes in C++
Stream classes in C++Stream classes in C++
Stream classes in C++
 
08. handling file streams
08. handling file streams08. handling file streams
08. handling file streams
 
Cpp file-handling
Cpp file-handlingCpp file-handling
Cpp file-handling
 
Pf cs102 programming-8 [file handling] (1)
Pf cs102 programming-8 [file handling] (1)Pf cs102 programming-8 [file handling] (1)
Pf cs102 programming-8 [file handling] (1)
 

Similar a FILE HANDLING IN C++. +2 COMPUTER SCIENCE CBSE AND STATE SYLLABUS

Input File dalam C++
Input File dalam C++Input File dalam C++
Input File dalam C++
Teguh Nugraha
 
Chapter28 data-file-handling
Chapter28 data-file-handlingChapter28 data-file-handling
Chapter28 data-file-handling
Deepak Singh
 
Files in C++.pdf is the notes of cpp for reference
Files in C++.pdf is the notes of cpp for referenceFiles in C++.pdf is the notes of cpp for reference
Files in C++.pdf is the notes of cpp for reference
anuvayalil5525
 
Basics of file handling
Basics of file handlingBasics of file handling
Basics of file handling
pinkpreet_kaur
 
Filesinc 130512002619-phpapp01
Filesinc 130512002619-phpapp01Filesinc 130512002619-phpapp01
Filesinc 130512002619-phpapp01
Rex Joe
 

Similar a FILE HANDLING IN C++. +2 COMPUTER SCIENCE CBSE AND STATE SYLLABUS (20)

Input File dalam C++
Input File dalam C++Input File dalam C++
Input File dalam C++
 
7 Data File Handling
7 Data File Handling7 Data File Handling
7 Data File Handling
 
Data file handling
Data file handlingData file handling
Data file handling
 
Chapter28 data-file-handling
Chapter28 data-file-handlingChapter28 data-file-handling
Chapter28 data-file-handling
 
File handling
File handlingFile handling
File handling
 
File management in C++
File management in C++File management in C++
File management in C++
 
Files in C++.pdf is the notes of cpp for reference
Files in C++.pdf is the notes of cpp for referenceFiles in C++.pdf is the notes of cpp for reference
Files in C++.pdf is the notes of cpp for reference
 
chapter-12-data-file-handling.pdf
chapter-12-data-file-handling.pdfchapter-12-data-file-handling.pdf
chapter-12-data-file-handling.pdf
 
Filesin c++
Filesin c++Filesin c++
Filesin c++
 
Basics of file handling
Basics of file handlingBasics of file handling
Basics of file handling
 
File handling
File handlingFile handling
File handling
 
File Management and manipulation in C++ Programming
File Management and manipulation in C++ ProgrammingFile Management and manipulation in C++ Programming
File Management and manipulation in C++ Programming
 
Unit-VI.pptx
Unit-VI.pptxUnit-VI.pptx
Unit-VI.pptx
 
Filesinc 130512002619-phpapp01
Filesinc 130512002619-phpapp01Filesinc 130512002619-phpapp01
Filesinc 130512002619-phpapp01
 
File handling in cpp
File handling in cppFile handling in cpp
File handling in cpp
 
FILE HANDLING.pptx
FILE HANDLING.pptxFILE HANDLING.pptx
FILE HANDLING.pptx
 
Filehandling
FilehandlingFilehandling
Filehandling
 
Filepointers1 1215104829397318-9
Filepointers1 1215104829397318-9Filepointers1 1215104829397318-9
Filepointers1 1215104829397318-9
 
File handling in C hhsjsjshsjjsjsjs.pptx
File handling in C hhsjsjshsjjsjsjs.pptxFile handling in C hhsjsjshsjjsjsjs.pptx
File handling in C hhsjsjshsjjsjsjs.pptx
 
File Handling
File HandlingFile Handling
File Handling
 

Más de Venugopalavarma Raja

Más de Venugopalavarma Raja (13)

Python Modules, Packages and Libraries
Python Modules, Packages and LibrariesPython Modules, Packages and Libraries
Python Modules, Packages and Libraries
 
Python Modules and Libraries
Python Modules and LibrariesPython Modules and Libraries
Python Modules and Libraries
 
FUNCTIONS IN PYTHON, CLASS 12 COMPUTER SCIENCE
FUNCTIONS IN PYTHON, CLASS 12 COMPUTER SCIENCEFUNCTIONS IN PYTHON, CLASS 12 COMPUTER SCIENCE
FUNCTIONS IN PYTHON, CLASS 12 COMPUTER SCIENCE
 
FUNCTIONS IN PYTHON. CBSE +2 COMPUTER SCIENCE
FUNCTIONS IN PYTHON. CBSE +2 COMPUTER SCIENCEFUNCTIONS IN PYTHON. CBSE +2 COMPUTER SCIENCE
FUNCTIONS IN PYTHON. CBSE +2 COMPUTER SCIENCE
 
LINKED LIST IN C++ +2 COMPUTER SCIENCE CBSE AND STATE SYLLABUS
LINKED LIST IN C++ +2 COMPUTER SCIENCE CBSE AND STATE SYLLABUSLINKED LIST IN C++ +2 COMPUTER SCIENCE CBSE AND STATE SYLLABUS
LINKED LIST IN C++ +2 COMPUTER SCIENCE CBSE AND STATE SYLLABUS
 
INHERITANCE IN C++ +2 COMPUTER SCIENCE CBSE AND STATE SYLLABUS
INHERITANCE IN C++ +2 COMPUTER SCIENCE CBSE AND STATE SYLLABUSINHERITANCE IN C++ +2 COMPUTER SCIENCE CBSE AND STATE SYLLABUS
INHERITANCE IN C++ +2 COMPUTER SCIENCE CBSE AND STATE SYLLABUS
 
CONSTRUCTORS IN C++ +2 COMPUTER SCIENCE
CONSTRUCTORS IN C++ +2 COMPUTER SCIENCECONSTRUCTORS IN C++ +2 COMPUTER SCIENCE
CONSTRUCTORS IN C++ +2 COMPUTER SCIENCE
 
CLASSES AND OBJECTS IN C++ +2 COMPUTER SCIENCE
CLASSES AND OBJECTS IN C++ +2 COMPUTER SCIENCECLASSES AND OBJECTS IN C++ +2 COMPUTER SCIENCE
CLASSES AND OBJECTS IN C++ +2 COMPUTER SCIENCE
 
ARRAYS IN C++ CBSE AND STATE +2 COMPUTER SCIENCE
ARRAYS IN C++ CBSE AND STATE +2 COMPUTER SCIENCEARRAYS IN C++ CBSE AND STATE +2 COMPUTER SCIENCE
ARRAYS IN C++ CBSE AND STATE +2 COMPUTER SCIENCE
 
POINTERS IN C++ CBSE +2 COMPUTER SCIENCE
POINTERS IN C++ CBSE +2 COMPUTER SCIENCEPOINTERS IN C++ CBSE +2 COMPUTER SCIENCE
POINTERS IN C++ CBSE +2 COMPUTER SCIENCE
 
Be happy Who am I
Be happy Who am IBe happy Who am I
Be happy Who am I
 
Be happy
Be happyBe happy
Be happy
 
Chess for beginers
Chess for beginersChess for beginers
Chess for beginers
 

Último

Kisan Call Centre - To harness potential of ICT in Agriculture by answer farm...
Kisan Call Centre - To harness potential of ICT in Agriculture by answer farm...Kisan Call Centre - To harness potential of ICT in Agriculture by answer farm...
Kisan Call Centre - To harness potential of ICT in Agriculture by answer farm...
Krashi Coaching
 
Russian Escort Service in Delhi 11k Hotel Foreigner Russian Call Girls in Delhi
Russian Escort Service in Delhi 11k Hotel Foreigner Russian Call Girls in DelhiRussian Escort Service in Delhi 11k Hotel Foreigner Russian Call Girls in Delhi
Russian Escort Service in Delhi 11k Hotel Foreigner Russian Call Girls in Delhi
kauryashika82
 

Último (20)

APM Welcome, APM North West Network Conference, Synergies Across Sectors
APM Welcome, APM North West Network Conference, Synergies Across SectorsAPM Welcome, APM North West Network Conference, Synergies Across Sectors
APM Welcome, APM North West Network Conference, Synergies Across Sectors
 
Call Girls in Dwarka Mor Delhi Contact Us 9654467111
Call Girls in Dwarka Mor Delhi Contact Us 9654467111Call Girls in Dwarka Mor Delhi Contact Us 9654467111
Call Girls in Dwarka Mor Delhi Contact Us 9654467111
 
Introduction to Nonprofit Accounting: The Basics
Introduction to Nonprofit Accounting: The BasicsIntroduction to Nonprofit Accounting: The Basics
Introduction to Nonprofit Accounting: The Basics
 
INDIA QUIZ 2024 RLAC DELHI UNIVERSITY.pptx
INDIA QUIZ 2024 RLAC DELHI UNIVERSITY.pptxINDIA QUIZ 2024 RLAC DELHI UNIVERSITY.pptx
INDIA QUIZ 2024 RLAC DELHI UNIVERSITY.pptx
 
Kisan Call Centre - To harness potential of ICT in Agriculture by answer farm...
Kisan Call Centre - To harness potential of ICT in Agriculture by answer farm...Kisan Call Centre - To harness potential of ICT in Agriculture by answer farm...
Kisan Call Centre - To harness potential of ICT in Agriculture by answer farm...
 
Arihant handbook biology for class 11 .pdf
Arihant handbook biology for class 11 .pdfArihant handbook biology for class 11 .pdf
Arihant handbook biology for class 11 .pdf
 
Nutritional Needs Presentation - HLTH 104
Nutritional Needs Presentation - HLTH 104Nutritional Needs Presentation - HLTH 104
Nutritional Needs Presentation - HLTH 104
 
Q4-W6-Restating Informational Text Grade 3
Q4-W6-Restating Informational Text Grade 3Q4-W6-Restating Informational Text Grade 3
Q4-W6-Restating Informational Text Grade 3
 
Holdier Curriculum Vitae (April 2024).pdf
Holdier Curriculum Vitae (April 2024).pdfHoldier Curriculum Vitae (April 2024).pdf
Holdier Curriculum Vitae (April 2024).pdf
 
Advanced Views - Calendar View in Odoo 17
Advanced Views - Calendar View in Odoo 17Advanced Views - Calendar View in Odoo 17
Advanced Views - Calendar View in Odoo 17
 
The Most Excellent Way | 1 Corinthians 13
The Most Excellent Way | 1 Corinthians 13The Most Excellent Way | 1 Corinthians 13
The Most Excellent Way | 1 Corinthians 13
 
Mattingly "AI & Prompt Design: The Basics of Prompt Design"
Mattingly "AI & Prompt Design: The Basics of Prompt Design"Mattingly "AI & Prompt Design: The Basics of Prompt Design"
Mattingly "AI & Prompt Design: The Basics of Prompt Design"
 
Advance Mobile Application Development class 07
Advance Mobile Application Development class 07Advance Mobile Application Development class 07
Advance Mobile Application Development class 07
 
Sports & Fitness Value Added Course FY..
Sports & Fitness Value Added Course FY..Sports & Fitness Value Added Course FY..
Sports & Fitness Value Added Course FY..
 
Interactive Powerpoint_How to Master effective communication
Interactive Powerpoint_How to Master effective communicationInteractive Powerpoint_How to Master effective communication
Interactive Powerpoint_How to Master effective communication
 
Software Engineering Methodologies (overview)
Software Engineering Methodologies (overview)Software Engineering Methodologies (overview)
Software Engineering Methodologies (overview)
 
Measures of Dispersion and Variability: Range, QD, AD and SD
Measures of Dispersion and Variability: Range, QD, AD and SDMeasures of Dispersion and Variability: Range, QD, AD and SD
Measures of Dispersion and Variability: Range, QD, AD and SD
 
Código Creativo y Arte de Software | Unidad 1
Código Creativo y Arte de Software | Unidad 1Código Creativo y Arte de Software | Unidad 1
Código Creativo y Arte de Software | Unidad 1
 
Russian Escort Service in Delhi 11k Hotel Foreigner Russian Call Girls in Delhi
Russian Escort Service in Delhi 11k Hotel Foreigner Russian Call Girls in DelhiRussian Escort Service in Delhi 11k Hotel Foreigner Russian Call Girls in Delhi
Russian Escort Service in Delhi 11k Hotel Foreigner Russian Call Girls in Delhi
 
Accessible design: Minimum effort, maximum impact
Accessible design: Minimum effort, maximum impactAccessible design: Minimum effort, maximum impact
Accessible design: Minimum effort, maximum impact
 

FILE HANDLING IN C++. +2 COMPUTER SCIENCE CBSE AND STATE SYLLABUS

  • 1. Data which are permanently stored in a computer are called Files. Word Processor creates document files. Database programs create files of information. Compiler read source file and generate executable files. A file itself is a bunch of bytes stored on some storage devices like Hard Disk, DVDs etc. A file, at its lowest level is a sequence or stream of bytes. At this level, the notation of data type is absent. In C++, file input/output facilities are implemented through a component header file named ‘fstream.h’.
  • 2. A stream is a sequence of bytes. In other words, a stream is a name given to a flow of data. Different streams are used to represent different kind of data flow. The ‘fstream library predefines operations for reading and writing Data to and from a Data File. It mainly consists of 3 classes that will perform file input and output. These are ‘ifstream’, ‘ofstream’ and ‘fstream’. ‘ifstream’ class ties a file with input file stream, ‘ofstream’ class ties a file with output file stream and ‘fstream’ class ties a file with both input and output file streams. 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 received data into the file. Data output to file Data input to program Disk File Program Write data to file Read data from file output stream input stream Click Me  ofstream Click Me  ifstream Data from program Raman, Balan, Soman Data from File Raman, Balan, Soman
  • 3. The ‘fstream.h’ Header File. The ‘fstream library predefines a set of operations for read and write operations with Data Files. It mainly defines 3 classes that will perform file input and output. These are ‘ifstream’, ‘ofstream’ and ‘fstream’. ‘ifstream’ class ties a file with input file stream, ‘ofstream’ class ties a file with output file stream and ‘fstream’ class ties a file with both input and output file streams. ios iostream istream ostream ifstream ofstream streambuf filebuf fstreambase fstream strstreambuf HOLDS-A Relationship. To get help of any class, type class name and press Ctrl+F1
  • 4. Functions of File Stream Classes. Class Functions filebuf It provides low level facilities. We can’t use filebuf directly. It is part of other file classes.It sets the file buffers to read and write. It contains open() and close() member function. fstreambase This is the base class for fstream, ifstream and ofstream classes. Therefore, it provides operations common to these file streams. It also contains open() and close() functions. Ifstream Being an input file stream class, It provides input operations for file. It inherits the functions get(), getline(), read() and other seekg() and tellg() functions supporting random acces. ofstream It provides output operations. It inherits put() and write() functions along with seekp() and tellp() functions supporting random acces. fstream It is a input as well as output file stream class. It provides support for simultaneous input and output operations. It inherits all the functions from istream and ostream classes through iostream class defined inside iostream.h file.
  • 5. The data files are the files that stores data pertaining to a specific application, for latter use. The data files can be stored in two ways. (i) Text Files. (ii) Binary Files. A text file stores information in ASCII characters. In text file each line of text is terminated with a special character known as End Of Line (EOL). In text files some internal translations take place when this EOL character is read or written. You can think of text files as sequence of bytes broken into subsequence with a special EOL character. Processing of this character leads to some internal translations taking place. It is not in the case of Binary Files. A binary file is just a file that contains information in the same format in which the information is held in memory there is no delimiter for a line. Also no translations occur in binary files. As a result, a binary files are faster and easier for a program to read and write than text files. As long as the file does not to read by people or need to be ported to a different type of system. Binary files are the best way to store program information. When you work with files in C++, unless you specify, files are by default considered and treated as text file.
  • 6. OPENING AND CLOSING FILES. To open a File, first declare an object, that satisfies our need. Write data into a file, use an object of class ‘ofstream’. Read data from a file use ‘ifstream’. For both read and write operation, use an object of class ‘fstream’. After that, you must specify the name of file you want to manipulate. This process is called ‘File Open”. Opening of a file is done in two ways. (i). Using the constructor function of the stream class. (ii). Using the function open(). Declaration of ifstream Object. (For Read Data From File.) Open using Constructor. ifstream a = “ABC.TXT”; Or ifstream a(“ABC.TXT”); Open using ‘open()’ ifstream a; a.open(“ABC.TXT”); Declaration of ofstream Object. (For write Data into File.) Open using Constructor. ofstream a = “ABC.TXT”; Or ofstream a(“ABC.TXT”); Open using ‘open()’ ofstream a; a.open(“ABC.TXT”); Declaration of fstream Object. (Both Read and Write.) Open using Constructor. fstream a (“ABC”, Mode); Or fstream a(“ABC”, Mode); Open using ‘open()’ fstream a; a.open(“ABC.TXT”, Mode);
  • 7. Data File Program Read From File Write into File I T I S O F S T Object Performs All Read/Write Operations. Stream class fstream { Description of member functions like open(), close(), getc(), put(), read(), write() etc. } Declaration of Object. fstream a = “ABC.TXT” ABC.TXT To close the link with the file “ABC.TXT”, Call ‘close()’ function in association with stream Object. Here a.close(); Stream representing the file ABC.TXT.
  • 8. To read and write data to and from a File, Simply use the << (Insertion) and >> (Extraction) Operators, in the same way that are used with cin and cout. And except that, instead of using cin and cout, substitute a stream that is linked to a file. ofstream a = “PLEDGE.TXT”; cout << “nINDIA IS MY COUNTRY ALL INDIANS ARE MY BROTHERS & SISTERS”; a << “nINDIA IS MY COUNTRY ALL INDIANS ARE MY BROTHERS & SISTERS”; Insert this caption into Console Output ‘cout’. ‘a’ is ofstream object, it is linked to the file PLEDGE.TXT. Hence the caption will be insert into the file PLEDGE.TXT instead of cout ifstream a = “STUDENT.TXT”; char name[20]; cin >> name; a >> name; Extract Name form Console input(KeyBoard). ‘a’ is ifstream object, and linked with the file STUDENT.TXT. Hence the Name stored in STUDENT.TXT will be extracted, and assigned in the array name[20];
  • 9. # include <iostream.h> # include <fstream.h> main() { char name[20]; int rollno; cout << "nPlease Enter Name & Roll No "; cin >> name >> rollno; cout << "nThe Name stored in STUDENT.TXT is “; cout << name << " " << rollno; } A simple program that will read Name & Roll No of a student and write them into a file name “STUDENT.TXT”. After that, extract Name & Roll No from that file. O F S T R E A M DATA FILE STUDENT.TXT I F S T R E A M ofstream a; ifstream b; ofstream a = "STUDENT.TXT"; // Click Me  ifstream b; // Click Me  a << “n” << name << " " << rollno; // Click Me  a.close(); b.open("student.txt"); // Click Me  b >> name >> rollno; // Click Me  Anil 100 Anil 100 ofstream – Write data into File. ifstream – Read data from File. Write Data through object ‘a’.. Read data through object ‘b’.
  • 10. The Concept of File Modes. File modes are certain constants, which are defined in the class ‘ios’. It describe how a file is to be used: to read data from it, to write to it, to append it and so on. The constructors and open() functions of class ifstrean and ofstream have two arguments. The first argument is the name of file to be open and the second one is File Mode. File mode is not compulsory. If you omit it, the function will provide default File Mode. ‘ifstream’ use the constant ios :: in and ‘ofstream’ use ios :: out as their default File Mode. The ‘fstream’ class does not provide a default mode. Therefore one must specify ‘file mode’ explicitly. To open a binary file, use ios :: binary along with other File Mode. To combine two or more File mode, use bitwise ‘OR’ ( | pipe symbol) operator. The deference between ios :: ate and ios :: app is that the ios :: app allows you to add data at the end of the file only while ios :: ate cause to move position at the end of file when open a file, after that one can read / write data anywhere in the file even overwrite old data also. Stream_name object ( “File Name”, file mode); Object.open(“File Name”, file mode); Eg: fstream a(“ABC.TXT”, ios :: in | ios :: out); Or fstream a; a.open(“ABC.TXT”, ios :: in | ios :: out); A file is closed .by disconnecting it with the stream. Its general form is Stream_Object.close(); Eg. a.close(); Click here to see all other ‘ios’ constants. 
  • 11. Constant Meaning Stream type ios :: in Opens file for reading. ifstream ios :: out Opens file for writing. this also opens the file in ios :: trunc mode by default. This means an existing file is truncated when opend. i.e. its previous contents are discarded. ofstream ios :: ate It seeks to end of file upon opening of the file. I/O operations can still occur anywhere whithin the file. ofstream ifstream ios :: app This cause all output to that file to be appended to the end. This value can be used with files capable of output. ofstream ios :: trunc This value causes the content of a pre-existing file to be destroyed and truncates the file to zero length. ofstream ios :: nocreate This causes the open () function to fail if the file does not exists. ofstream ios :: noreplace This cause the open() function to fail if the file already exists. This is used when you want to create a new file at every time. ofstream ios :: binary This cause a file to be opened in binary mode. By default files are opened in text mode. When a file is opened in text mode various character translations may take place such as carriage return into new line. However no such character translation occur in files opened in binary mode. ofstream ifstream
  • 12. STEPS TO PROCESS A FILE IN YOUR PROGRAM. 1. Determine the type of link required. 2. Declare a stream for the desired type of link. 3. Attach the desired file to the stream. 4. Now process as required. 5. Close the File link with stream. 1. Determine the type of link required. This step requires the identification of type of link required. If the program want to get data stored in a file, first transfer the data from File to memory. This type of link is said to be File-to-Memory link. After some processing the data is to be sent from memory to file. This type of link is said to be Memory-to-File link. Some situation demands both type of links, File-to-Memory and Memory-to-File, then two way link can be created. Predefine string ‘cin’ is an example of File-to-Memory link. Since all devices are treated as file, keyboard is also treated as file. With ‘cin’ data comes from the file keyboard to memory. With ‘cout’ data goes memory to the file ‘Monitor’ hence a Memory-to-File link is established.
  • 13. 2. Declare a stream for the desired type of link. After determining the type of link required, the next step is to create a stream for it. For different type of links different stream classes are used for stream declaration. For File-to-Memory type of link ‘ifstream’ class stream is declared. For Memory-to-File type of link ‘ofstream’ class stream is declared. For two way type of link (Both File-to-Memory and Memory-to-File) ‘fstream’ class object is declared. Type of Link. Used for Stream Class Example File-to-Memory Read Data from a File. Bring data from file to memory for further processing. ifstream ifstream a; Memory-to-File Write Data into a File. Send processed Data from Memory to File. ofstream ofstream a; File-to-Memory Memory-to-File Both Read and Write data from and to a file. Both input and output purpose. fstream fstream a;
  • 14. 3. Attach the desired file to the stream. After declaring streams, the next step is to link the file with the declared stream. This is done by opening the desired file. A file can be opened in two ways. Using constructor and using open() methode. 4. Now process as required. Under this step, processing is required is performed. 5. Close the File link with stream. At this step the link between file and stream will be closed. This is performed through close() method. General form of constructor. Stream-Name Object (“File Name”, Mode); General form of open() function. Object.open(“File Name”, Mode); ifstream a = “ABC.TXT”; ifstream b(“ABC.TXT”, ios :: in); ifstream b(“ABC.TXT”, ios :: in | ios :: binary); ifsream b(“ABC.TXT”, ios :: in | ios :: binary | ios :: ate); ofsream a=“ABC.TXT”; ofstream a(“ABC.TXT”, ios :: out); ifstream a(“ABC.TXT”, ios :: in | ios :: binary); ofstream a(“ABC.TXT”, ios :: out | ios :: binary | ios :: ate); File Opening Modes ios :: in  Input ios :: out  Output ios :: ate  At End ios :: app  Append ios :: trunc  Truncate ios :: binary ios :: nocreate ios :: noreplace
  • 15. // Read Name & Roll No of several Students and write them into a file named “STUDENT.TXT”. # include <iostream.h> # include <fstream.h> main() { char name[20]; int rollno; char ans; do { cout << "nnPlease Enter Name & Roll No "; cin >> name >> rollno; cout << "nnDo You Want To Continue (Y/N) ?. "; cin >> ans; }while( ans=='y' || ans == 'Y'); a.close(); } a << "n" << name << " " << rollno; // Click Me Repeat this while ans = Yes  O F S T R E A M DATA FILE STUD.TXT Anil 100 ofstream a("STUD.TXT“, ios :: out); // Click Me 
  • 16. //Read Name & Roll No from the file “STUDENT.TXT”. # include <iostream.h> # include <fstream.h> main() { char name[20]; int roll; ifstream a(“STUD.TXT”, ios :: in); while( !a.eof() ) { a >> name >> roll; cout << "nName “ << name << “Roll No “ << roll; } a.close(); } I F S T R E A M Anil 100 Babu 101 Sunil 102 DATA FILE STUDENT.TXT Click Me  eof() Function will returns non-zero(True Value) if end-of-file is encountered while reading otherwise returns zero(False Value). General Form is : Object.eof() Eg. a.eof()  Check whether the EOF is reached on the associated file. (Here “STUDENT.TXT”) EOF is a constant indicating that end-of-file has been reached on a file. Sunil 102 Repeat while Not EOF Returns EOF  Anil 100 Babu 101 Repeat this while not EOF 
  • 17. Detecting EOF. You can detect when the end of file has been reached or not by using the member function eof(). It will returns non-zero if EOF is encountered otherwise return zero. ifstream ifs = “STUD.DAT”  Opens STUD.DAT through the input file stream ‘ifs’. if ( ! ifs )  When the file can’t open ifstream object ‘ifs’ becomes zero. cout << “File Can’t Open”; else cout << “File Opened”; while ( ! ifs.eof() ) { } Read Data While Not EOF. while ( ifs ) { } The Stream Object always denote the status of the Stream.. Status value zero indicates that the stream is not ready for read or write operation. Non-zero value indicates that the stream is ready. Read data While status is Non-Zero Repeat this while not EOF  Repeat this While status Is Non-Zero. 
  • 18. # include <iostream.h> # include <fstream.h> main() { char name[20]; int rollno, m1, m2, m3, tot; char ans; ofstream ofs(“STUDENT.DAT”, ios :: out); ifstream ifs; do { cout << "nnPlease Enter Name & Roll No "; cin >> name >> rollno; cout << "nnPlease Enter 3 Marks "; cin >> m1 >> m2 >> m3; ofs << “n” << name << “ “ << rollno << “ “ << m1 << “ “ << m2 << “ “ << m3 << “ “ << m1+m2+m3; cout << "nDo You Want To Continue (Y/N) ?. "; cin >> ans; }while( ans=='y' || ans == 'Y'); ofs.close(); Read Name,Roll No, marks in 3 subjects of several Students and write them into a file named ‘STUDENT.DAT’ Ifs.open(“STUDENT.DAT”, ios :: in); while ( ! ifs.eof()) { ifs >> name >> rollno >> m1 >> m2 >> m3 cout << “n” << name << “ “ << rollno << “ “ << m1 << “ “ << m2 << “ “ << m3 << “ “ << m1+m2+m3; } // loop ends. } // end of main() Anil 100 34 26 40 100 Babu 101 28 32 30 90 Sunil 102 37 23 25 85 DATA FILE STUDENT.DAT Anil 100 34 26 40 100 Click Me  Babu 101 28 32 30 90Sunil 102 37 23 25 85 EOF Read each Record from “STUDENT.DAT”. Repeat this Click Me  Repeat this while not EOF  Returns EOF  Anil 100 34 26 40 100 Babu 101 28 32 30 90 Sunil 102 37 23 25 85
  • 19. // Store details of some items into a file named “ITEM.DAT” # include <iostream.h> # include <fstream.h> main() { char name[20], ans; int code, qty; float price; ofstream ofs("ITEM.DAT", ios :: out); ifstream ifs; ofs.close(); ifs.open("ITEM.DAT", ios :: in); } do { cout << "nnPlease Enter Item Name, code, qty and Price "; cin >> name >> code >> qty >> price; ofs << "n" << name << " " << code << " " << qty << " " << price; cout << "nnDo You Want to Continue (Y/N) ?. "; cin >> ans; }while(ans == 'y' || ans == 'Y'); while( ! ifs.eof() ) { ifs >> name >> code >> qty >> price; cout << "n" << name << " " << code << " " << qty << " " << price; } Pencil 100 25 5.25 Pen 101 50 7.50 Ink 102 35 12.75 DATA FILE ITEM.DAT EOF O F S T R E A M I F S T R E A M ofs ifs Click Me  Click Me  Pencil 100 25 5.25 Pen 101 50 7.50 Ink 102 32 12.75 Returns EOF  Repeat this while ans = Yes  Pencil 100 25 5.25Pen 101 50 7.50Ink 102 32 12.75
  • 20. # include <iostream.h> # include <conio.h> # include <fstream.h> main() { char empname[20], desig[20], ans; int empno; float basic; ofstream emp("EMPLOYEE.DAT", ios :: out); ifstream ifs; do { cout << "nnPlease Enter Name, Emp No, Designation and Basic Pay "; cin >> empname >> empno >> desig >> basic; emp << "n" << empname << " " << empno << " " << desig << " " << basic; cout << "nDo You Want to Continue (Y/N) ?. "; cin >> ans; }while(ans == 'y' || ans == 'Y'); emp.close(); ifs.open("EMPLOYEE.DAT", ios :: in); while( ! ifs.eof() ) { ifs >> empname >> empno >> desig >> basic; cout << "n" << empname << " " << empno << " " << desig << " " << basic; } getch(); } Repeat this while ans = Yes  Repeat this while not EOF 
  • 21. # include <iostream.h> # include <conio.h> # include <fstream.h> main() { char name[20], ans; int roll; float per; ofstream pass("PASS.DAT", ios :: out); ofstream fail("FAIL.DAT", ios :: out); ifstream ifs; do { cout << "nPlease Enter Item Name, Roll No and % of Marks "; cin >> name >> roll >> per; cout << "nnDo You Want to Continue (Y/N) ?. "; cin >> ans; }while(ans == 'y' || ans == 'Y'); pass.close(); fail.close(); ifs.open("PASS.DAT", ios :: in); while( ! ifs.eof() ) { ifs >> name >> roll >> per; cout << "n" << name << " " << roll << " " << per; } ifs.close(); ifs.open(“FAIL.DAT", ios :: in); while( ! ifs.eof() ) { ifs >> name >> roll >> per; cout << "n" << name << " " << roll << " " << per; } ifs.close(); } if (per>=50) pass << "n" << name << " " << roll << " " << per; else fail << "n" << name << " " << roll << " " << per; Read name, roll no and % of Marks, if % of marks >=50 then write this record into PASS.DAT else write it in FAIL.DAT. Raman 100 58 Balan 101 45Click Me 
  • 22. Changing the Behavior of Streams. The default behavior of ifstream is reading data from a text file. And if the file mode is ios :: in | io :: binary then reading is performed on a binary file. The default behavior of ofstream is ios :: out. When we use this mode, if the file does not exists it will create a new one else it will erase all previous data. We can change this mode by specifying any of following file mode. To read from or write to a binary file, the file mode must contain ios :: binary in combination with other file mode. ios :: app To retain previous contents of the file and to append to the end of existing file. Ios :: ate Place the file pointer at the end of file but one can write data anywhere in the file. Ios :: trunc It causes the existing file to be truncated. ios :: nocreate If the file does not exist, this file mode ensure that no file is created and hence open() fails. However, if the file exists it gets opened. ios :: noreplace If the file does not exist, a new file gets created but if the file already exist, the open() fails.
  • 23. SEQUENTIAL I/O WITH FILES. Sequential read and write from and into the file is called Sequential access. The functions get() and put() are capable of handling a single character at a time. The function getline() lets you handle multiple characters at a time. Another pair of function read() and write() are capable of reading and writing block of binary data. The Function get() will read a byte (one character) from the stream and put() will write a byte into the stream. The general form of get() and put() is given bellow. istream & get ( char &ch); ostream & put (char ); # include <iostream.h> # include <conio.h> # include <fstream.h> main() { char ch=0; ofstream ofs="PLEDGE.TXT"; ifstream ifs; cout << "nEnter a National Pledge "; while( ch != 27) // ASCII of Escape is 27 { ch = getche(); ofs.put(ch); } ofs.close(); ifs.open("PLEDGE.TXT"); cout << "nnnThe Content of PLEDGE.TXT isnn"; while ( ! ifs.eof() ) { ifs.get(ch); cout.put(ch); } cout << "nnnPress any Key....."; getch(); } Getting Each Character and put it in PLEDGE,TXT Repeat this while ch != ESC  // Read National Pledge & write it in a File PLEDGE.TXT. Getting Each Character from File and put it in MONITORRead each Character while not EOF 
  • 24. The other forms of get() Function. istream & get ( char *buf, int num, char delim = ‘n’); Reads more characters into a character array named ‘buf’ until either ‘num’ characters have been read or the character specified by delim has been encountered. The array will be NULL terminated by get(). If no delimiter character is specified, by default a new line character (’n’) acts as a delimiter. int get(); It will read a single character from the stream. # include <iostream.h> # include <conio.h> main() { char name[30]; cout << "nEnter Your Full Name "; cin.get(name, 30, '.‘ ); cout << "nnHai " << name; getch(); } OUTPUT Enter Your Full Name Anil Kumar P. Hai Anil Kumar P # include <iostream.h> # include <conio.h> main() { char name[30]; cout << "nEnter Your Full Name "; cin >> name; cout << "nnHai " << name; getch(); } OUTPUT Enter Your Full Name Anil Kumar P. Hai Anil Read either 30 Characters or the ‘full stop’ has been encountered. Read a single word only. See Difference
  • 25. Another Prototype of getline() Function. get(char *buf, int num, char delim). And getline ( char * buf, int num, char delim = ‘n’); are same. getline() will read several characters from input stream and put them in the array named buf until either num character have been read or the character specified by delim is encountered. The difference between get(char *buf, int num, char delim) and getline(char *buf, int num, char delim) is that getline() reads and removes the delimiter character from the input stream if it is encoutered which is not done by get(char *buf, int num, char delim) function. # include <iostream.h> # include <conio.h> main() { char name[30]; int age; cout << "nEnter Your Full Name"; cin.get ( name, 30, ’.’ ); cout << “nnEnter Age “; cin >> age; cout << name << “ Your Age is “ << age; getch(); } OUTPUT Enter Your Full Name Anil Kumar P. Enter Age Name Anil Kumar P Your Age -22827 # include <iostream.h> # include <conio.h> main() { char name[30]; int age; cout << "nEnter Your Full Name"; cin.getline ( name, 30, ’.’ ); cout << “nnEnter Age “; cin >> age; cout << name << “ Your Age is “ << age; getch(); } OUTPUT Enter Your Full Name Anil Kumar P. Enter Age 28 Name Anil Kumar P Your Age 28 Age will not read. Because of Delimiter character is present in input stream.
  • 26. The read () and write () functions. istream & read (char *buf, int size); This function will read a block of binary data from the input stream and put them in the buffer (Memory) named ‘buf. The size of buffer is mentioned by an integer value ‘size’. The address of the variable must be type cast to char *. ostream & write (char * buf, int size); This function will write a block of binary data into the output stream and put them in the buffer (Memory) named ‘buf. The size of buffer is mentioned by an integer value ‘size’. The address of the variable must be type cast to char *. # include <iostream.h> # include <fstream.h> main() { char name[20], ans; int age; ofstream ofs = "STUDENT.DAT"; ifstream ifs; do { cout << "nEnter Name & Age "; cin >> name >> age; ofs.write( name, 20); ofs.write( (char *) &age, 2); cout << "nDo You Want to Continue (Y/N) ?. "; cin >> ans; }while(ans=='Y' || ans == 'y'); ofs.close(); ifs.open("STUDENT.DAT"); while( !ifs.eof() ) { ifs.read( name, 20); ifs.read( (char *) &age,2); cout << "nn" << name << ", " << age; } ifs.close(); } Cast to char * Repeat this while not EOF 
  • 27. Reading and Writing Class Objects. These functions handle all data members of an object as a single unit, using the computer’s internal representation of data. Read() and write() functions will read and write entire data of an object from and to memory, byte by byte. The length of an object is obtained by ‘sizeof’ operator. # include <iostream.h> # include <fstream.h> struct student { char name[20]; int age; }; main() { student a; char ans; int age; ofstream ofs = "STUDENT.DAT"; ifstream ifs; do { cout << "nEnter Name "; cin.getline(a.name, 20); cout << "nEnter Age "; cin >> a.age; ofs.write( (char *) &a, sizeof(a)); cout << "nDo You Want to Continue (Y/N) ?. "; cin >> ans; cin.ignore(); }while(ans=='Y' || ans == 'y'); ofs.close(); ifs.open("STUDENT.DAT"); while( !ifs.eof() ) { ifs.read( (char *) &a, sizeof(a)); cout << "nn" << a.name << ", " << a.age; } ifs.close(); } Consider Name and Age as a single unit of size 22 bytes, and write all these 22 bytes into the file STUDENT.DAT Read Name and Age as a single unit of size 22 bytes from STUDENT.DAT Cast to char * Repeat this while not EOF 
  • 28. # include <iostream.h> # include <conio.h> # include <fstream.h> main() { bank a; char ans; ofstream ofs = "BANK.DAT"; ifstream ifs; do { cout << "nDo You Want to Continue (Y/N) ?. "; cin >> ans; cin.ignore(); }while(ans=='Y' || ans == 'y'); ofs.close(); ifs.open("BANK.DAT"); while( !ifs.eof() ) { } ifs.close(); getch(); } class bank { char name[20]; int acno; float amount; public: void open() { cout << "nEnter Name "; cin.getline(name, 20); cout << "nEnter A/c No & Amount. "; cin >> acno >> amount; } void out() { cout << "n" << name << ", " << acno << ", " << amount; } }; a.open(); //Click Me ofs.write( (char *) &a, sizeof(a)); //Click Me ifs.read( (char *) &a, sizeof(a)); //Click Me a.out(); //Click Me BANK.DAT Anil Kumar 100 10000 Anil Kumar 100 10000 Do this while ans = Yes  Repeat this while Not EOF  Anil Kumar 100 10000
  • 29. More about Reading and Writing Class Objects. Sometimes a need arise to treat a group of different data as a single unit. For Example a record in a file can have several fields of different types and entire record may be required to be processed in one unit. Read() and write() functions will read and write data in multiples of the size of the object. It include used and unused bytes. Suppose name[20] is a character array of size 20. And the data assigned in ‘name’ is ‘ANIL”. In this case first four byres are used. Remaining 16 bytes are unused. When performs read() and write() all 20 bytes will be considered. struct Student { char name [20]; int rollno; } a = { “ANIL”,100 }; A N I L 0 Used 100 Unused char name[20] roll DATA FILE A N I L 0 100 B A L A C H A N D R A N 0 101 H A R I 0 102 Read() & Write() whole 22 bytes. With the inclusion of unused bytes, each records have get equal Length. STUDENT.DAT
  • 30. FILE POINTERS AND RANDOM ACCESS. Moving directly to any location is called random access. Every file maintains two pointer called get pointer and put pointer which tell position in the file where reading and writing will take place. Get pointer is the position where reading of data will take place and put pointer is the position where writing of data will take place. By using seekg(), seekp(), tellg() and tellp() functions one can place read-write position at any place and process data at that position. seekg() and seekp() functions will place get and put pointer at specified position. General form of these functions are given bellow. istream & seekg(long pos) : will place ‘get-pointer’ at the position specified by pos. ofstream & seekp(long pos) : will place ‘put-pointer’ at the position specified by pos. istream & seekg( long, seek_dir) will place ‘get-pointer’ at the position specified by pos relative to seek_dir. ‘seek_dir’ is an enumaration defined in iostream.h. ofstream & seekp( long, seek_dir) will place ‘get-pointer’ at the position specified by pos relative to seek_dir. Seek_dir constants are ios :: beg  Refers to beginning of the file. ios :: cur  Refers to current position in the file. ios :: end  Refers to end of the file. Some Example are given bellow
  • 31. DATA FILE STUDENT.DAT A N I L 0 100 B A L A C H A N D R A N0 101 H A R I 0 102 S U N I L 0 102 struct Student { char name [20]; int rollno; } a = { “ANIL”,100 }; Beging of file Assuse that here Is the current Position. EOF seekg(22, ios :: cur); moves get pointer 10 bytes back from end of the file. Click Me  seekg(22, ios :: beg); moves get pointer 10 bytes from beginning of the file. Click Me seekg(44, ios :: beg); moves get pointer 10 bytes from current position. Click Me seekg(-44, ios :: end); moves get pointer 10 bytes from current position. Click Me seekg(-22, ios :: beg); ERROR. Can’t Move back from Beginning of File. Click Me  seekg(22, ios :: end); ERROR. Can’t Move forward from end of File. Click Me  tellg() returns the position of get pointer in bytes. Click tellp() returns the position of put pointer in bytes. Me seekg(-44,ios::end); cout << “Cur Position“<< tellg();        Each Record has 22 Bytes.
  • 32. # include <iostream.h> # include <conio.h> # include <fstream.h> main() { Student a; fstream fs("STUDENT.DAT", ios :: in | ios :: out | ios :: binary); char ans; do { a.input(); fs.write( (char *) &a, sizeof(a)); cout << "nnnContinue (Y/N) ?. "; cin >> ans; cin.ignore(); }while(ans=='y' || ans=='Y'); fs.seekg(0); while( ! fs.eof() ) { fs.read( (char *) &a, sizeof(a)); a.out(); } getch(); } class Student { char name[20]; int rollno; public: void input() { cout << "nnEnter Name "; cin.getline(name,20); cout << "nnRoll No "; cin >> rollno; } void out() { cout << "n" << name << " " << rollno; } }; Function for inputing Data. Open the File in Read, Write, Binary modes. Write all 22 bytes into the file STUDENT.DAT. Read from STUDENT.DAT. Do this while ans = Yes  Repeat this while not EOF 
  • 33. # include <iostream.h> # include <conio.h> # include <fstream.h> # include <ctype.h> main() { Student a; ifstream ifs; char ans; ofstream ofs("STUD.DAT", ios :: out | ios :: binary ); do { a.input(); ofs.write( (char *) &a, sizeof(a)); cout << "nnnDo You Want To Continue (Y/N) ?. "; cin >> ans; cin.ignore(); }while(toupper(ans) == 'Y'); ofs.close(); ifs.open("STUD.DAT", ios :: in | ios :: binary); while ( ifs.read( (char *) &a, sizeof(a)) ) a.out(); } class Student { char name[20], grade; int rollno, m1, m2, m3, tot; float avg, per; void input() { cout << "nEnter Name "; cin.getline(name,20); Cout << “nEnter Roll No “; cin >> rollno; cout << "nnEnter 3 Marks "; cin >> m1 >> m2 >> m3; calculate(); } void calculate() { tot = m1+m2+m3; per = (tot/300.0)*100; if (per >=90) grade = 'A'; else if (per >=80) grade = 'B'; else if (per >=70) grade = 'C'; else if (per >=60) grade = 'D'; else if (per >=50) grade = 'E'; else grade = 'F'; } void out() { clrscr(); gotoxy(10,4); cout << "Senior School Certificate Exam"; cout<<"nName :"<<name<<"t Roll No :"<<rollno; cout<<"nTot. Marks "<<tot<<"t% of Marks"<<per; cout << "nnGrade : " << grade; getch(); } }; Do this while upper(ans) = Yes  Read Each Record while Not EOF 
  • 34. Searching. The process of locating desired record in a file is called Searching. Let us imagine a Binary file STUDENT.DAT contains following records. struct Student { char name [20]; int rollno; float per; }; A N I L 0 STUDENTS.DAT HARI KUMAR 100 78.00 ANIL KRISHNAN 101 69.25 SURESH BABU 102 72.50 THOMAS MATHEW 103 92.00 JACOB PAUL 104 55.80 JOHN MATHEW 105 84.00 DAVID VARGHEESE 106 59.50 Object of Student float per; (4 Bytes) int rollno; (2 Bytes) char name[20]; (20 Bytes) All Records have equal size. 20 (Name) + 2(rollno) + 4 (per) = 26 Bytes.
  • 35. ALGORITHAM. 1. Define a structure or class ‘STUDENT’ contains name, Roll No & % of Marks. And relevant Member Functions. class STUDENT { …. }; 2. Declare an object of above class definition. And an int variable ‘x’, which is used to store the roll no we want to searched for ?. Declare int flag = 0; If locate given Roll No then the flag is set to 1. STUDENT a; int x, flag = 0; 3. Declare an ‘ifstream’ object ‘ifs’ and open the file. ifstream ifs = “STUDENT.DAT”; 4. Print the caption “Which Roll No You want to searched for ?“ and input value of x. cout << “Which Roll No You want to searched for ?“; cin >> x. 5. Repeat following steps while not EOF. while ( ! Ifs.eof() ) { read (…..)…… } i. Read each record from the input file stream. read( (char *) &a, sizeof(a) ); ii. If its Roll No = x (Roll No to be searched) then set ‘flag = 1’ and break from loop. if ( a.rollno == x ) { flag = 1; break; } 6. If flag == 1 then print details of Object if( flag==1) a.out(); else cout << “ Not Found.”; 7. Else Print an Error Message “Record Not Found.”
  • 36. START END STUDENT a; ifstream ifs = “STUDENT.DAT”; Int x, flag = 0; if can’t Open cout << “Roll No ?. “; cin >> x; if not EOF Read Record from File. if a.rollno == x flag = 1; break if flag == 1 cout << a.name << a.rollno; OR a.out();cout << “Not Found.” YES NO YES NO NO YES TEST CASES BY CLICK File Can’t Open. Click Me Can’t Find. Click Me Found Record. Click Me Case File Can’t Open  NO YES Case : Can’t Find  Case : Find Record. 
  • 37. # include <iostream.h> # include <conio.h> # include <fstream.h> main() { Student a; fstream fs("STUDENT.DAT", ios :: in | ios :: binary); int roll, flag = 0; if( !fs ) { cout << "nFile Can't Open"; return 0; } cout << "nEnter Roll No "; cin >> roll; while ( fs.read( (char *) &a, sizeof(a)) ) { if (a.rollno == roll) { flag = 1; break; } } if(flag == 1) { cout << "nGiven Record Located "; a.out(); } else { cout << "nGiven Roll No Not Found."; } getch(); } struct Student { char name[20]; int rollno; void input() { cout << "nEnter Name "; cin.getline(name,20); cout << "nRoll No "; cin >> rollno; } void out() { cout << "n" << name << " “ << rollno; } }; Read each record & Compare with given roll no  TEST CASES BY CLICK Can’t Find. Click Me Found Record. Click Me
  • 38. # include <iostream.h> # include <conio.h> # include <fstream.h> # include <ctype.h> main() { Student a; ifstream ifs; char ans; ofstream ofs("STUD.DAT", ios :: app | ios :: binary ); do { a.input(); ofs.write( (char *) &a, sizeof(a)); cout << "nnnDo You Want To Continue (Y/N) ?. "; cin >> ans; cin.ignore(); }while(toupper(ans) == 'Y'); ofs.close(); ifs.open("STUD.DAT", ios :: in | ios :: binary); while ( ifs.read( (char *) &a, sizeof(a)) ) a.out(); } class Student { char name[20], grade; int rollno, m1, m2, m3, tot; float avg, per; void input() { cout << "nEnter Name "; cin.getline(name,20); Cout << “nEnter Roll No “; cin >> rollno; cout << "nnEnter 3 Marks "; cin >> m1 >> m2 >> m3; } void calculate() { tot = m1+m2+m3; per = (tot/300.0)*100; if (per >=90) grade = 'A'; else if (per >=80) grade = 'B'; else if (per >=70) grade = 'C'; else grade = ‘D'; void out() { cout <<"n"<< name <<“,:“ << rollno << “, “ << tot << “, “ << per << “, " << grade;} }; Appends while upper(ans) = Yes  Appending Data. To append data, Open the file with ios :: out and ios app specifications. When opening a file in ios :: app mode, the previous records is retained and new data gets appended to the file. Ios :: app will add new records at end. Write each record into STUD.DAT Read Each Record while Not EOF  
  • 39. Inserting data in sorted file. To insert data in a sorted file, firstly find its appropriate position. Then copy all records prior to this determined position to a temporary file followed by the new record and then rest of the records. 1. Find appropriate position of the record to be inserted in the file STUD.DAT. 2. Copy the records prior to determined position to a temporary file sat TEMP.DAT. 3. Write new record to temporary file TEMP.DAT. 4. Copy rest of records from STUD.DAT to temporary file TEMP.DAT. 5. Delete the file STUD.DAT and rename file TEMP.DAT as STUDENT.DAT by issuing the following commands. remove(“STUD.DAT”); and (rename(“TEMP.DAT”, “STUD.DAT”);) OR 5. Overwrite existing file STUD.DAT with records in the temporary file TEMP.DAT. Name Roll No % of Marks Anil Kumar 100 88.00 Hari Kumar 101 82.50 Krishna Kumar 102 77.00 Babu Paul 104 60.00 Thomas Mathew 105 55.00 Sivaraman 103 65.00
  • 40. Thomas Mathew 105 55.00 Name Roll No % of Marks Anil Kumar 100 88.00 Hari Kumar 101 82.50 Krishna Kumar 102 77.00 Babu Paul 104 60.00 Sivaraman 103 65.00 Thomas Mathew 105 55.00 Name Roll No % of Marks Hari Kumar 101 82.50 Krishna Kumar 102 77.00 Babu Paul 104 60.00 STUDENT.DAT Sivaraman 103 65.00 TEMP.DAT Inserting data in sorted file. To insert data in a sorted file, firstly find its appropriate position. Then copy all records prior to this determined position to a temporary file followed by the new record and then rest of the records. Show Copy  Anil Kumar 100 88.00 Anil Kumar 100 88.00 Hari Kumar 101 82.50 Krishna Kumar 102 77.00 Sivaraman 103 65.00 Babu Paul 104 60.00 Thomas Mathew 105 55.00 Records prior to determined position. Records after the determined position.
  • 41. # include <iostream.h> # include <conio.h> # include <fstream.h> # include <ctype.h> # include <stdio.h> class Student { char name[20]; public: int roll; void input() { cout << "nEnter Name "; cin.getline(name,20); cout << "nnEnter Roll NO "; cin >> roll; }; void out() { cout << "nn" << name << ", " << roll; } }; main() { Student s, ns; char ans; ifstream b; ofstream a("STUD.DAT", ios :: app | ios :: binary); ofstream t("TMP.DAT", ios :: out | ios :: binary); do { s.input(); a.write( (char *) &s, sizeof(s)); cout << "nConinue (Y/N) ?. "; cin >> ans; cin.ignore(); }while(toupper(ans)=='Y'); a.close(); b.open("STUD.DAT", ios :: in | ios :: binary); cout << "nEnter new record "; ns.input(); while( b.read( (char*) &s, sizeof(s)) && s.roll <= ns.roll) { t.write( (char*) &s, sizeof(s)); } t.write( (char*) &ns, sizeof(ns)); if ( !b.eof() ) do { t.write( (char*) &s, sizeof(s)); }while( b.read( (char*) &s, sizeof(s)) ); b.close(); t.close(); remove("STUD.DAT"); rename("TMP.DAT", "STUD.DAT"); b.open("STUD.DAT", ios :: in | ios :: binary); while ( b.read( (char*) &s, sizeof(s)) ) s.out(); getch(); }
  • 42. To Delete a record, the following operations are carried out. Determine the position of the record to be deleted. Copy all records other than the record to be deleted to a temporary file say TEMP.DAT Do not copy the record to be deleted to temporary file. Copy rest of records to temporary file. Delete original file and rename TEMP.DAT as the name of original file. TO DELETE A RECORD, COPY ALL RECORDS OTHER THAN THE RECORDS TO BE DELETE INTO A TEMPORARY FILE TEMP.DAT. Deleting a Record.
  • 43. Thomas Mathew 105 55.00 Name Roll No % of Marks Anil Kumar 100 88.00 Hari Kumar 101 82.50 Babu Paul 104 60.00 TEMP.DAT Anil Kumar 100 88.00 Hari Kumar 101 82.50 Thomas Mathew 105 55.00 Name Roll No % of Marks Anil Kumar 100 88.00 Hari Kumar 101 82.50 Krishna Kumar 102 77.00 Babu Paul 104 60.00 STUDENT.DAT All Records Other Than The Records To Be Delete Are Copied Into A Temporary File Temp.Dat. Record to be Delete. Show Copy  YES Shall It Delete ? NO Don’t Write Anil Kumar 100 88.00 Hari Kumar 101 82.50 Krishna Kumar 102 77.00 Babu Paul 104 60.00 Thomas Mathew 105 55.00
  • 44. # include <iostream.h> # include <conio.h> # include <fstream.h> # include <ctype.h> # include <stdio.h> main() { Student s; char ans; int del_rol; ofstream a("STUD.DAT", ios::app | ios::binary); ofstream t("TEMP.DAT", ios::out | ios::binary); ifstream b; do { s.input(); a.write( (char *) &s, sizeof(s)); cout << "nnConinue (Y/N) ?. "; cin >> ans; cin.ignore(); }while(toupper(ans)=='Y'); a.close(); b.open("STUD.DAT", ios :: in | ios :: binary); cout << "nEnter Roll No You Want to Delete "; cin >> del_rol; while( b.read( (char*) &s, sizeof(s)) ) { if (s.roll != del_rol) t.write( (char*) &s, sizeof(s)); } b.close(); t.close(); remove("STUD.DAT"); rename("TEMP.DAT", "STUD.DAT"); b.open("STUD.DAT", ios :: in | ios :: binary); while ( b.read( (char*) &s, sizeof(s)) ) s.out(); getch(); } class Student { char name[20]; public: int roll; void input() { cout << "nnEnter Name "; cin.getline(name,20); cout << "nnEnter Roll NO "; cin >> roll; }; void out() { cout << "nn" << name << ", " << roll; } }; Copy all records except one to TEMP  Add records while uppor(ans) = Y 
  • 45. Modifying Data. To modify a record the file is opened in I/O (both read and write) modes and locate the record we want to modify. It is done by read each record from file and compare its ‘key field’ (Here Roll no) with given roll no. After locating the required record, it was modified in memory. Finally the file pointer is once again placed at the beginning of this record then record is rewritten. Algoritham. Define Class STUDENT and Declare an object ‘a’ of STUDENT. STUDENT a; Declare ‘int rol’ to store roll no of the record we want to edit. Declare ‘fstream fs(“STUD.DAT”, ios :: in | ios :: out | ios :: ate | ios binary) to read and write records to and from the file STUD.DAT. Ask Roll No we want to edit. cout << “Roll NO ?. “; cin >> rol; Repeat following while not EOF. while ( !fs.eof()) Read each record from the file. fs.read( (char*) &a, sizeof(a)); If it is the record we want to edit then Input New Data, move ‘put pointer’ at the beginning of the record and write. if (a.roll == rol ) { a.input(); fs.seekp(-1*sizeof(a), ios :: cur); fs.write( “char *) &a, sizeof(a) ); }
  • 46. Read each Record from File. fs.read( (char *) &a, sizeof(a)); If it’s Roll No == Given Roll No if (a.roll == edit_roll) Read Roll No to be EDIT. cout << “Enter Roll No “; cin >> edit_roll; Move ‘get pointer’ to beginning of the file. fs.seekg(0, ios :: beg); Input new Details. a.input(); Move ‘put-pointer’ to beginning of record. a.seekp(--22, ios :: cur); Write modified record. fs.write ( (char *) &a, sizeof(a)); If Not EOF ( while ( !fs.eof() ) ) Yes No If Not EOF On EOF STOP Can’t Find. Click Me Found Record. Click Me 
  • 47. Thomas Mathew 104 55.00 Name Roll No % of Marks Anil Kumar 100 88.00 Hari Kumar 101 82.50 Kirshan kemar 103 60.00 TEMP.DAT Anil Kumar 100 88.00 Hari Kumar 101 82.50 fstream fs( “STUD.DAT”, ios :: in | ios :: out | ios :: ate | ios :: binary); Student a; int edit_roll; cout << “Enter Roll NO “; cin >> edit_roll; fs.seekg(0, ios :: beg); while ( fs.read( (char *) &a, sizeof(a) ) { if(a.roll == edit_roll) { a.input(); fs.seekp(-22, ios :: cur); fs.write( (char *) &a, sizeof(a)); } } void Student :: input() { cout << “nEnter Name & Roll No “; cin.getline(a.name, 20); cin >> a.roll; } Show Editing   After reading the record, ‘get pointer’ is positioned at this point. ‘put pointer’ Record to be edited Edit_roll = 103  KRISHNA KUMAR 103 60.00
  • 48. # include <iostream.h> # include <conio.h> # include <fstream.h> # include <ctype.h> # include <stdio.h> main() { Student s; char ans; int edit_rol; fstream a("STUDENT.DAT", ios :: in | ios :: out | ios :: ate | ios :: binary); do { s.input(); a.write( (char *) &s, sizeof(s)); cout << "nConinue (Y/N) ?. "; cin >> ans; cin.ignore(); }while(toupper(ans)=='Y'); cout << "nEnter Roll No You Want to Edit ?."; cin >> edit_rol; a.clear(); a.seekg(0, ios :: beg); while( a.read( (char*) &s, sizeof(s)) ) { if (s.roll == edit_rol) { cout << "nCurrent DETAILS "; s.out(); cout << "nPlease Enter New DETAILS"; s.input(); a.seekp( -22, ios :: cur); a.write( (char*) &s, sizeof(s)); } } a.clear(); a.seekg(0, ios :: beg); while( a.read( (char*) &s, sizeof(s)) ) s.out(); a.close(); } class Student { char name[20]; public: int roll; void input() { cin.seekg(0, ios :: beg); cout << "nEnter Name "; cin.getline(name,20); cout << "nEnter Roll NO "; cin >> roll; }; void out() { cout << "nn" << name << ", " << roll; } }; Move put_pointer to the beginning of the Record.
  • 49. ERROR HANDLING DURING FILE I/O. Some times during file operations, error may also creep in. To check for errors and to ensure smooth processing, C++ file stream inherit ‘stream-state’ members from the ios class that stores current status of a file. enum io_state { goodbit = 0x00, // no bit set: all is ok eofbit = 0x01, // at end of file failbit = 0x02, // last I/O operation failed badbit = 0x04, // invalid operation attempted hardfail = 0x80 // unrecoverable error }; Name Value eofbit 1 when end of file else 0 failbit 1 when a non-fatal error has occurred else 0. badbit 1 when a fatal error has occurred else 0. goodbit 0 value. Function Meaning int bad() Returns non zero if an invalid operation is attempted or any unrecoverable error has occurred. int eof() Returns non-zero if EOF is encountered otherwise zero int fail() Returns non-zero when an operation has failed. int good() Returns non zero if no error has occurred else return 0. clear() Reset the error state so that further operations can be attempted.
  • 50. Thomas Mathew 105 55.00 Name Roll No % of Marks Anil Kumar 100 88.00 Hari Kumar 101 82.50 Babu Paul 104 60.00 TEMP.DAT Anil Kumar 100 88.00 Hari Kumar 101 82.50 Thomas Mathew 105 55.00 Name Roll No % of Marks Anil Kumar 100 88.00 Hari Kumar 101 82.50 Krishna Kumar 102 77.00 Babu Paul 104 60.00 STUDENT.DAT Anil Kumar 100 88.00 Hari Kumar 101 82.50 Krishna Kumar 102 77.00 Babu Paul 104 60.00 Thomas Mathew 105 55.00 All Records Other Than The Records To Be Delete Are Copied Into A Temporary File Temp.Dat. Record to be Delete. Show Copy  Shall It Delete ?
  • 51. A file is a bunch of bytes stored on some storage device. C++’s fstream library predefines a set of operations for handling file I/O. The ifstream class ties a file to the input stream for input. The ofstream class ties a file to the output stream for output. The fstream class ties a file to the stream for both input and output. The classes defined inside fstream.h derive from classes under iostream.h A file can be opened in two ways (i) using the constructor function of the stream class. (ii) Using the function open(). A file mode describes how a file is to be used, read it, write to it, append it and so on. Different file modes are ios::in, ios::out, ios::app, ios::ate, ios::trunc, ios::nocreate, ios::noreplace. A file can be closed i.e its connection with the stream is terminated using function close(). In order to process files, follow these steps (i) determine the type of link. (ii) Declare a stream accordingly. (iii) Link file with the stream, (iv) Process as required. (v) Delink the file with the stream. The function get(), put() read and write data respectively one byte at a time.
  • 52. The get() and getline() read characters into character array pointed to by buf until either num characters have been read or the delimiter character is encountered. The get() does not extract the delimiter character from the input stream while the getline reads and removes the delimiter character from the input stream. A block 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() return the position of get-pointer and put-pointer respectively in a file stream. The function eof() determines the end of file by returning true for end of file otherwise by returning false. C++ also provides certain error handling functions that ensure smooth working of the program. These functions are eof(), bad(), fail(), and good(). LET US REVISE  
  • 53.
  • 54. 65526 65525 65524 65523 65522 65521 65520 65519 65518 65517 65516 65515 65514 65513 65512 65511 65510 65509 p 65524 a=15, b   Show Order  6 5 5 0 0 6 5 5 0 1 6 5 5 0 2 6 5 5 0 3 6 5 5 0 4 6 5 5 0 5 6 5 5 0 6 6 5 5 0 7 6 5 5 0 8 6 5 5 0 9 6 5 5 1 0 6 5 5 1 1 6 5 5 1 2 6 5 5 1 3 6 5 5 1 4 6 5 5 1 5 6 5 5 1 6 6 5 5 1 7 6 5 5 1 8 6 5 5 1 9 6 5 5 2 0 6 5 5 2 1 6 5 5 2 2 6 5 5 2 3 6 5 5 2 4 6 5 5 2 5 6 5 5 2 6 6 5 5 2 7   p 65524 p 4 0 1 5 4 0 1 9 4 0 2 2 FREE A 3.14 10 8 7 9 4012
  • 55. a Click Me  c   c 6   anil 6   Click Me  Show Order  6 5 5 0 0 6 5 5 0 1 6 5 5 0 2 6 5 5 0 3 6 5 5 0 4 6 5 5 0 5 6 5 5 0 6 6 5 5 0 7 6 5 5 0 8 6 5 5 0 9 6 5 5 1 0 6 5 5 1 1 6 5 5 1 2 6 5 5 1 3 6 5 5 1 4 6 5 5 1 5 6 5 5 1 6 6 5 5 1 7 6 5 5 1 8 6 5 5 1 9 6 5 5 2 0 6 5 5 2 1 6 5 5 2 2 6 5 5 2 3 6 5 5 2 4 6 5 5 2 5 6 5 5 2 6 6 5 5 2 7
  • 56. Modifying Data. To modify a record the file is opened in I/O (both read and write) modes and locate the record we want to modify. It is done by read each record from file and compare its ‘key field’ (Here Roll no) with given roll no. After locating the required record, it was modified in memory. Finally the file pointer is once again placed at the beginning of this record then record is rewritten. Thomas Mathew 105 55.00 Name Roll No % of Marks Anil Kumar 100 88.00 Hari Kumar 101 82.50 Babu Paul 104 60.00 TEMP.DAT Anil Kumar 100 88.00 Hari Kumar 101 82.50 Thomas Mathew 104 55.00 Name Roll No % of Marks Anil Kumar 100 88.00 Hari Kumar 101 82.50 Kirshan kemar 103 60.00 TEMP.DAT Anil Kumar 100 88.00 Hari Kumar 101 82.50 Edit the record who’s roll no = 103.