Module V File
Module V File
using C++
Course Code: ES203
MODULE V-File Handling
Ms. Garima Srivastava
Asstt. Professor
Dept Of CSE/IT ASET
AUUP Lucknow
Streams
2
Streams
• A stream is a general name given to a flow of data in an input/output
situation.
• A stream is a sequence of bytes.
• The source stream that provide data to the program is called as Input
Stream.
• The destination stream receives output from the program is called Output
Stream.
• For this reason, streams in C++ are often called iostreams.
• An iostream can be represented by an object of a particular class.
You’ve already seen numerous examples of the cin and cout stream
objects used for input and output.
3
Advantages of Streams
• Old-fashioned C programmers may wonder what
advantages there are to using the stream classes for I/O
instead of traditional C functions such as printf() and
scanf() and—for files—fprintf(), fscanf(), and so on.
• One reason is that the stream classes are less prone to
errors.
• If you’ve ever used a %d formatting character when you
should have used a %f in printf(), you’ll appreciate this.
There are no such formatting characters in streams,
because each object already knows how to display itself.
This removes a major source of program bugs. 4
• Second, you can overload existing operators and
functions, such as the insertion (<<) and extraction (>>)
operators, to work with classes you create.
• This makes your classes work in the same way as the
built-in types, which again makes programming easier
and more error free (not to mention more aesthetically
satisfying).
5
Stream Class Hierarchy
6
Stream Class Hierarchy
7
Stream Class Hierarchy
• The ios class is the base class for the iostream hierarchy.
–contains many constants and member functions common
to input and output operations of all kinds.
–also contains a pointer to the streambuf class, which
contains the actual memory buffer into which data is read or
written and the low-level routines for handling this
data.
• The istream and ostream classes are derived from ios
and are dedicated to input and output, respectively.
8
• The istream class contains such member functions as
get(), getline(), read(), and the extraction (») operators,
whereas ostream contains put() and write() and the
insertion («) operators.
• The iostream class is derived from both istream and
ostream by multiple inheritance.
– used with devices, such as disk files, that may be opened for
both input and output at the same time.
9
• The ifstream class is used for creating input file objects.
• The ofstream class is used for creating output file objects.
• To create a read/write file the fstream class should be
• used.
10
Disk File I/O with Streams
• Disk files require a different set of classes than files used
with the keyboard and screen.
• These are ifstream for input, fstream for input and output,
and ofstream for output.
• Objects of these classes can be associated with disk files
and you can use their member functions to read and write
to the files.
• The ifstream, ofstream, and fstream classes are declared
in the FSTREAM.H file.
11
• This file also includes the IOSTREAM.H header file, so
there is no need to include it explicitly;
• FSTREAM.H takes care of all stream I/O.
• To create an input stream, declare an object of type
ifstream.
• To create an output stream, declare an object of type
ofstream.
• To create an input/output stream, declare an object of
type fstream.
12
• For example, this fragment creates one input stream, one
output stream and one stream capable of both input and
output:
• ifstream in: // input;
• ofstream out; // output;
• fstream io; // input ad output
• Once you have created a stream, one way to associate it
with a file is by using the function open( ).
• This function is a member function of each of the three
stream classes.
13
• void ifstream::open(const char *filename, openmode
mode=ios::in);
• void ofstream::open(const char *filename, openmode
mode=ios::out | ios::trunc);
• void fstream::open(const char *filename, openmode
mode=ios::in | ios::out);
• Here filename is the name of the file, which can include a
path specifier.
• The value of the mode determines how the file is opened.
14
• It must be a value of type openmode, which is an
enumeration defined by ios that contains the following
value:
ios::app Append to end of file
15
• You can combine two or more of these values.
• ios::app: causes all output to that file to be appended to
the end. Only with files capable of output.
• ios::ate: causes a seek to the end of the file to occur
when the file is opened.
• ios::out: specify that the file is capable of output.
• ios::in: specify that the file is capable of input.
• ios::binary: causes the file to be opened in binary mode.
• By default, all files are opened in text mode.
16
• The following fragment opens an output file called test:
ofstream mystream;
mystream.open("test");
• Since the mode parameter to open( ) defaults to a value
appropriate to the type of stream being opened, there is
no need to specify its value in the preceding example.
• If open( ) fails, the stream will evaluate to false when used
in a Boolean expression.
• You can make sure of this fact to confirm that the open
operation succeeded by using a statement like this:
17
if (!mystream) {
cout << "Cannot open file.\n";
// handle error
}
• In general, you should always check the result of a call to
open( ) before attempting to access the file.
18
• You can also check to see if you have successfully
opened a file by using the is_open( ) function, which is a
member of fstream, ifstream and ofstream. It has a
prototype as:
• bool is_open( );
• It returns true if the stream is linked to an open file and
false otherwise. For example, the following check if
mystream is currently opened:
• if (!mystream.is_open())
• cout << "File is not open.\n";
• // ... 19
• Although it is entirely proper to open a file by using the
open( ) function, most of the time you will not do so
because the ifstream, ofstream and fstream classes have
constructor functions that automatically open files.
• The constructor functions have the same parameters and
defaults as the open( ) function.
• Therefore, the most common way you will see a file
opened is shown in this example:
• ifstream mystream("myfile"); // open a file
20
• To close a file use the member function close( ).
• For example, to close the file linked to a stream called
mystream, use this statement,
– mystream.close( );
• The close( ) function takes no parameters and returns no
value.
• You can detect when the end of an input file has been
reached by using the eof( ) member function of ios. It has
a prototype:
21
bool eof( );
• It returns true when the end of the file has been encountered and
false otherwise.
• Always test for the end-of-file condition before processing data
read from an input file stream.
• Once a file has been opened, it is very easy to read textual data
from it or write formatted textual data to it. simply use the << and
>> operators the same way you do when performing console I/O,
except that instead of using cin and cout, substitute a stream that
is linked to a file.
• A file produced by using << is a formatted text file, and any file
read by >> must be a formatted text file. 22
File I/O is a five-step process:
1. Include the header file fstream in the program.
2. Declare file stream object.
3. Open the file with the file stream object.
4. Use the file stream object with >>, <<, or other
input/output functions to read from or write to the file.
5. Close the file.
23
Creating an output file
#include <iostream>
#include <fstream>
using namespace std;
int main( ) {
ofstream fout("test"); // create output file
if (!fout) {
cout << "Cannot open output file.\n";
return 1;
}
fout << "Hello\n";
24
fout.close( );
ifstream fin("test"); // open input file
if (!fin) {
cout << "Cannot open input file.\n";
return 1;
}
char str[80];
fin >> str;
cout << str;
fin.close( );
return 0; }
25
Reads strings
#include <iostream>
#include <fstream>
using namespace std;
int main( int argc, char *argv[]) {
if (argc!=2) {
cout << "Usage: WRITE <filename>\n";
return 1;
}
ofstream out(argv[1]); // output file
26
• if (!out) {
• cout << "Cannot open output file.\n";
• return 1;
• }
• char str[80];
• cout << "Write strings to disk, '$' to stop\n";
• do {
• cin >> str;
• out << str << endl;
• } while (*str !='$');
• out.close( );return 0;} 27
• In Standard C++ the open( ) does not support the parameter that
specified the file's protection mode that is supported by old C++.
• When using an old C++ library, you must explicitly specify both the
ios::in and the ios::out mode values.
• Finally, in the old I/O system, the mode parameter could also
include either ios::nocreate or ios::moreplace. These values are
not supported by Standard C++
28
Unformatted, binary I/O
• C++ supports a wide range of unformatted file I/O functions.
• The unformatted functions give you detailed control over how files
are written and read.
• The lowest-level unformatted I/O functions are get( ) and put( ).
You can read a byte by using get( ) and write a byte by using
put( ).
• These functions are member functions of all input and output
stream classes, respectively.
• The get( ) function has many forms, but the most commonly used
version is shown here, along with put( ):
• istream &get(char &ch);
29
• ostream &put(char &ch);
• To read and write blocks of data, use read( ) and write( )
functions, which are also member functions of the input
and output stream classes, respectively. Their prototypes
are:
• istream &read(char *buf, streamsize num);
• ostream &write(const char *buf, streamsize num);
• The read( ) function reads num bytes from the stream and
puts them in the buffer pointed to by buf.
• The write( ) function writes num bytes to the associated
stream from the buffer pointed by buf. 30
• These functions think about data in terms of bytes (type
char). They don’t care how the data is formatted, they
simply transfer a buffer full of bytes from and to a disk file.
• The parameters to write() and read() are the address of
the data buffer and its length.
• The address must be cast to type char, and the length is
the length in bytes (characters), not the number of data
items in the buffer.
31
• The streamsize type is some form of integer. An object of type
streamsize is capable of holding the largest number of bytes that
will be transferred in any I/O operation.
• If the end of file is reached before num characters have been
read, read( ) stops and the buffer contains as many characters as
were available. You can find out how many characters have been
read by using the member function gcount( ), which has this
prototype:
• streamsize gcount( );
• It returns the number of characters read by the last unformatted
input operation.
32
Reading From a file
#include <iostream> ifstream in(argv[1], ios::in |
#include <fstream> ios::binary);
using namespace std; if (!in) {
int main(int argc, char *argv[]) { cout << "Cannot open file\n";
char ch; return 1;}
if (argc!=2) { while (!in.eof( )) {
cout << "Usage: PR <filename>\ in.get(ch);
n"; cout << ch;}
return 1;} in.close( );
return 0;}
33
Writing to a File
#include <iostream> if (!out) {
#include <fstream> cout << "Cannot open file\n";
using namespace std;
return 1;}
int main(int argc, char *argv[]) {char
ch; cout << "Enter a $ to stop\n";
if (argc!=2) { do {cout << ": ";
cout << "Usage: WRITE <filename>\ cin.get(ch);
n";
out.put(ch);
return 1;
} while (ch!='$')
}
ofstream out(argv[1], ios::out | out.close( );
ios::binary); return 0;
}
34
Writing Strings
• #include <iostream> • }
• #include <fstream> • double num = 100.45;
• #include <cstring> • char str[] = "This a test";
• using namespace std; • out.write((char *) &num,
• int main( ) { sizeof(double));
• ofstream out("test", ios::out | • out.write(str, strlen(str));
ios::binary); • out.close( );
• if (!out) { • return 0;
• cout << "Cannot open file\n"; • }
• return 1;
35
• Note that the type cast (char *) inside the call to write( ) is
necessary when outputting a buffer that is not defined as
a character array.
• Because of C++ strong type checking, a pointer of one
type will not automatically be converted into a pointer of
another type.
• The same applies to read( ).
36
Reading Strings
• #include <iostream> • double num;
• #include <fstream> • char str[80];
• using namespace std; • in.read((char *) &num,
• int main( ) { sizeof(double));
• ifstream in("test", ios::in | • in.read(str, 14);
ios::binary); • str[14] = '\0'; // null terminate
• if (!in) { str
• cout << "Cannot open input • cout << num << " " << str;
file\n"; • in.close( );
• return 1; • return 0;
• }
37
More unformatted I/O functions
• In addition to the form shown earlier, there are several different
ways in which the get( ) function is overloaded. The prototypes for
the three most commonly used overloaded forms are:
1. istream &get(char *buf, streamsize num);
The first form reads characters into the array pointed to by buf, until
either num-1 characters have been read, a new line is found, or the
end of the file has been encountered.
The array pointed to by buf, will be null terminated by get( ).
If the newline character is encountered in the input stream, it is not
extracted.
Instead, it remains in the stream until the next input operation.
38
2. istream &get(char *buf, streamsize num, char delim);
• The second form reads characters into the array pointed to by buf,
until either num-1 characters have been read, the character
specified by delim has been found, or the end of file has been
encountered.
• The array pointed to by buf, will be null terminated by
get( ).
• If the delimiter character is encountered in the input stream, it is
not extracted. Instead, it remains in the stream until the next input
operation.
39
3. int get( );
• The third overloaded form of get( ) returns the next
character from the stream.
• It returns EOF if the end of file is encountered.
• This form of get( ) is similar to the C getc( ) function.
• Another function that performs input is getline( ).
• It is a member function of each input stream class.
40
• Its prototypes are:
• istream &getline(char *buf, streamsize num);
• The first form reads characters into the array pointed to
by buf until either num-l characters have been read, a
newline character is found, or the end of the file has been
encountered. The array pointed to by buf will be null
terminated by getline( ). If the newline character is
encountered in the input stream, it is extracted, but it is
not put into buf.
41
• istream &getline(char *buf, streamsize num, char
delim);
• The second form reads characters into the array pointed
to by buf until either num-l characters have been read, the
character specified by delim has been found, or the end
of file has been encountered. The array pointed to by buf
will be null terminated by getline( ). If the newline
character is encountered in the input stream, it is
extracted, but it is not put into buf.
42
• The difference between get( ) and getline( ) is that
getline( ) reads and removes the delimiter from the input
stream; get( ) does not.
• You can obtain the next character in the input stream
without removing it from that stream by using peek( ).
This function is a member function of the input stream
classes and its prototype is
• int peek( ); It returns the next character in the stream; it
returns EOF if the end of file is encountered
43
Appending a new data
int main()
{
ofstream OFileObject;
OFileObject.open ("D:\\ExampleFile.txt", ios::app);
OFileObject << "I am writing to a file opened from program.\n";
cout<<"Data has been appended to file";
OFileObject.close();
}
44
File Pointers
• The C++ I/O system manages two pointers associated with a file.
• One is the get pointer, which specifies where in the file the next
input operation will occur.
• The other is the put pointer, which specifies where in the file the
next output operation will occur.
• Each time an input or output operation takes place, the
appropriate pointer is automatically sequentially advanced.
• However, by using the seekg( ) and the seekp( ) functions, it is
possible to access the file in a nonsequential fashion .
45
Random access
• In C++ I/O system, you perform random access by using
the seekg( ) and seekp( ) functions, which are members
of the input and output stream classes, respectively. Their
most common forms are:
• istream &seekg(off_type offset, seekdir origin);
• ostream &seekp(off_type offset, seekdir origin);
• Here off_type is an integer type defined by the ios that is capable
of containing the largest valid value that offset can have.
• seekdir is an enumeration defined by ios that has these values:
46
• ios::beg
– Seek from beginning
• ios::cur
– Seek from current location
• ios::end
• Seek from enThe seekg( ) function moves the associated file's
current get pointer offset number of bytes from the specified
origin.
• The seekp( ) function moves the associated file's current put
pointer offset number of bytes from the specified origin.
47
• You can determine the current position of each file pointer
by using these member functions:
– pos_type tellg( );
– pos_type tellp( );
• Here pos_type is an integer type defined by the ios that is capable
of holding the largest value that defines a file position.
• There are overloaded versions of seekg( ) and seekp( ) that move
the file pointers to the location specified by the returned value of
tellg( ) and tellp( ). Their prototypes are:
• istream &seekg(pos_type position);
• ostream &seekp(pos_type position);
48
• The following program allows you to change a specific
character in a file. Specify a file name on the command
line, filled by the number of the byte in the file you want to
change, followed by the new character. The file is opened
for read/write operations.
49
#include <fstream>
#include <cstdlib>
using namespace std;
int main(int argc, char *argv[ ] )
{
if (argc!=4) {
cout <<"Usage: CHANGE <filename> <byte> <char>\n;
return 1;}
fstream out(argv[1], ios::out | ios::binary);
50
if (!out) {
cout << "Cannot open file\n";
return 1;}
out.seekp(atoi(argv[2]),ios::beg);
out.put(*argv[3]);
out.close( );
return 0;
}
51
Use of get pointer
• #include <fstream>
• #include <cstdlib>
• using namespace std;
• int main(int argc, char *argv[ ] ) {
• char ch;
• if (argc!=3) {
• cout <<"Usage: LOCATE <filename> <loc>\n";
• return 1;
• }
• istream in(argv[1], ios::in | ios::binary); 52
#include <fstream>
#include <cstdlib>
using namespace std;
int main(int argc, char *argv[ ] ) {
char ch;
if (argc!=3) {
cout <<"Usage: LOCATE <filename> <loc>\n";
return 1;
}
istream in(argv[1], ios::in | ios::binary);
53
if (!in) {
cout << "Cannot open file\n";
return 1;
}
in.seekg(atoi(argv[2]),ios::beg);
while (!in.eof( )) {
in.get(ch);
cout << ch;
}
in.close( );
return 0;} 54
Reading /Writing a complete Object
class student
{
private:
char name[30];
int age;
public:
void getData(void)
{ cout<<"Enter name:"; cin.getline(name,30);
cout<<"Enter age:"; cin>>age;
}
55
void showData(void)
{
cout<<"Name:"<<name<<",Age:"<<age<<endl;
}
};
int main()
{ student s;
ofstream file;
file.open("aaa.txt",ios::out);
if(!file) {
56
cout<<"Error in creating file.."<<endl;
return 0;
}
cout<<"\nFile created successfully."<<endl;
//write into file
s.getData(); //read from user
file.write((char*)&s,sizeof(s)); //write into file
file.close(); //close the file
cout<<"\nFile saved and closed succesfully."<<endl;
//re open file in input mode and read data
57
ifstream file1;
file1.open("aaa.txt",ios::in);
if(!file1){
cout<<"Error in opening file..";
return 0;
}
file1.read((char*)&s,sizeof(s));
s.showData();
file1.close();
return 0;
} 58
Modifying a Content
#include<fstream>
using namespace std;
int main()
{fstream ofstream_ob;
ofstream_ob.open("File1.txt", ios::in|ios::out|ios::binary);
char ch;int pos;
while(ofstream_ob)
{ch = ofstream_ob.get();
if(ch =='e')
{
59
//Going one byte position back from the current put pointer position
pos= ofstream_ob.tellg();
ofstream_ob.seekp(pos-1);
ofstream_ob.put('X');
}
}
//Setting the EOF flag off, to allow the access of file again for
reading/writing
ofstream_ob.clear();
cout<<"The modified content of the file : \n";
//Taking the get pointer at the beginning of the file 60
ofstream_ob.seekg(0, ios::beg);
//Reading and displaying the modified file
while(ofstream_ob)
{
ch = ofstream_ob.get();
cout<<ch;
}
ofstream_ob.close();
return 0;}
61
Moving to a particular record
#include < fstream.h >
class student{
private:
int no;
char name[25];
float fee;
public:
void getdata()
{ cout << "\n\n Roll Number : " ;
cin >> no;
cout << "\n\n Name : "; cin >> name;
62
cout << "\n\n Fees : ";
cin >> fee;
}
void putdata()
{
cout << "\n\n Roll Number : " << no;
cout << "\n\n Name : " << name;
cout << "\n\n Fees : " << fee;
}
};
int main() { student s1; fstream stdfile; clrscr();
63
stdfile.open("student.dat",ios::out|ios::in|ios::binary);
char ch;
do
{s1.getdata();
stdfile.write((char *)&s1,sizeof(s1));
cout<<"\n Continue? y/n : ";
cin>>ch;
} while (ch=='Y'||ch=='y');
clrscr();
stdfile.seekg(0,ios::end); //moves the get pointer to the end of file
64
int endposition=stdfile.tellg(); //returns current position of get
int n=endposition/sizeof(s1); // total number of records
cout << "\n\n There are " << n <<" records in the file \n";
int num;
cout << "\n\n Enter the no. of the record which want to read :";
cin >> num;
int position=(num-1)*sizeof(s1);
stdfile.seekg(position);
stdfile.read((char *)&s1,sizeof(s1));
s1.putdata(); return 0;}
65
Modifying a Record
class abc {
int roll;
char name[20];
public:
void getdata(int, char[]);
void update(int, int, char[]);
void testcase1();
void testcase2();
void putdata();
};
void abc::putdata()
{ cout << "roll no: ";
66
cout << roll;
cout << "\nname: ";
cout << name;
}
void abc::getdata(int a, char str[])
{ roll = a;
strcpy(name, str);
}
void abc::update(int rno, int r, char str[])
{ int pos, flag = 0;
fstream fs;
fs.open(“the.dat", ios::in | ios::binary | ios::out);
67
while (!fs.eof()) {
pos = fs.tellg();
fs.read((char*)this, sizeof(abc));
if (fs) {
if (rno == roll) {
flag = 1;
getdata(r, str);
fs.seekp(pos);
fs.write((char*)this, sizeof(abc));
putdata();
break;} }}
68
fs.close();
if (flag == 1)
cout << "\n record successfully modified \n";
else
cout << "\n record not found \n";
}
void abc::testcase1()
{ int rno, r;
char name[20];
rno = 1;
r = 11;
strcpy(name, “Sumit");
69
// call update function with new values
update(rno, r, name);
}
void abc::testcase2()
{
int rno, r;
char name[20];
rno = 4;
r = 14;
strcpy(name, “Sahil"); update(rno, r, name); }
70
int main()
{
abc s;
s.testcase1();
s.testcase2();
return 0;
}
71
Deleting a Record
class student {
int roll;
char name[20];
public:
void getdata()
{
cin>>roll>>name;
}
void putdata(){
cout<<roll<<name;
}
};
72
Deleting a Record
int main()
{student s;
int pos, flag = 0,rno;
cout<<“enter the roll no. to be deleted”;cin>>rno;
ifstream ifs;
ifs.open(“old.dat", ios::in | ios::binary);
ofstream ofs;
ofs.open("temp.dat", ios::out | ios::binary);
while (!ifs.eof()) {
ifs.read((char*)&s, sizeof(student));
if (ifs) {
73
if (rno == s.roll) {
flag = 1;
cout << "The deleted record is \n";
// display the record
s.putdata();
}
else {
// copy the record of “old" file to "temp" file
ofs.write((char*)&s, sizeof(student));
}
}
}
74
ofs.close();
ifs.close();
// delete the old file
remove(“old.dat");
// rename new file to the older file
rename("temp.dat", “old.dat");
if (flag == 1)
cout << "\n record successfully deleted \n";
else
cout << "\n record not found \n";
}
75
• WAP to search for a particular record and delete it from
the file.
76