Download as doc, pdf, or txt
Download as doc, pdf, or txt
You are on page 1of 8

C++

CHAPTER 11: Working with Files


Introduction:
A file is a bunch of bytes stored on some storage device like tapes, magnetic disks, etc. It serves the
purpose of storing data permanently on the hard disk. Thus, most computer programs work with
files. In C++, file I/O operations are implemented through a component header file, fstream.h of C+
+ standard library. This header file contains a set of classes that define file handling methods.
Before going further, let us understand different terms related to file handling.

File:
File consists of related records maintained in some pre-arranged order.
Record:
Record consists of group of fields related to any object. They are maintained row wise.
Field:
A set of characters, used together to represent a specific data element. A particular column in a file
represents field.
Character:
Character consists of numbers (0-9), alphabets (A-Z, a-z) or special symbols (+ - * / = $ # etc.)
One character occupies one byte and as you know, one byte equals to eight bits.
The above relationship can be explained with the help of following diagram.

Field1 Field2
File

Record Record Record

Records E.O.F.
Field Field Field

Character Character Character

Bit Bit Bit

Streams as an Interface:
The file operations make use of streams as an interface between the program and the file.
A stream is a sequence of bytes.
Each stream is associated with a particular class, which contains member functions and definitions
for dealing with that particular kind of data flow.
Input stream – A stream that supplies data to the program.
It reads data from the file and hands it over to the program.
Output stream - A stream that receives data from the program. It writes the received data into the
file.

Types of data files:


There are two types of files
 text files
 binary files
Text files
They store information in ASCII characters.

By Darshit Shah Page 1 of 8


C++

In text files, each line of text is terminated (delimited) with a special character known as EOL (end
of line) character. Some internal translations take place when EOL is encountered.
Binary files
They contain information in the same format in which information is held in memory. In binary
files, there is no delimiter for a line. Also, no translations occur in binary files. Binary files are
faster and easier for a program to read and write than text files.

EOF
At the end of each file, there is a special character stored automatically by the compiler/operating
system denoting the End of the File (shortly known as EOF).

Classes for File Stream Operations:


C++ contains a set of classes for the management of I/O system. Three important classes are
ifstream (input file stream), ofstream (output file stream) and fstream(input as well output file
stream). We must have to use any one of these classes for the purpose of file management.
If we want to write data to the file on the hard disk, we have to associate our file with ofstream
class. If we want to read data from the file that has been previously stored on the hard disk, we have
to associate our file with ifstream class. If we want to carry out both the operations simultaneously,
we have to associate that file with fstream class.

ifstream class: Contains open() with default input mode. Inherits the function get(), getline(),
read(), seekg(), tellg() functions from istream.
ofstream class: Contains open() with default output mode. Inherits put(), seekp(),tellp(), and
write() functions from ostream.
fstream class: Contains open() with default input mode. Inherits all the functions from istream and
ostream classes through iostream.

Opening of a File:

We have to define the stream first and then link the stream to the filename. This can be done by two
different methods as mentioned below.
1. Using the constructor function of the class.
E.g. ofstream outfile(“Result”);
“Result” is the name of file physically created on the harddisk. This file is referred to by us
in our program with the name outfile (logical file). Since we have created object from
ofstream, the data can only be written to “result” file.
E.g ifstream infile(“Result”);
Here, we are attaching ifstream with file “Result” and that means we want to read the
contents of the file “Result” that has been already existing on the hard disk. Here, infile is
the logical file name that is used to refer to physical file “Result”.
2. Using the member function open() of the class.
E.g. ofstream outfile;
Outfile.open(“Result”);

ifstream infile;
infile.open(“Results”);

fstream inoutfile;
inoutfile.open(“Results”); // Default: Read mode only.
Inoutfile.open(“Results”,ios::out); // You can only write to “Result” file.
If the file already exists on the hard disk, it will be destroyed and new file
will be created with same name.

By Darshit Shah Page 2 of 8


C++

The following table summarizes different file mode parameters.

Parameters Meaning Notes


ios::out Open file for writing only Also deletes the content of the
file if it exists. No need to
specify if the object is created
from ofstream class.
ios::in Open file for reading only. No need to specify if the object
is created from ifstream class.
ios::app Append to end-of-file ios::app allows to add data at
the end of the file only while
ios::ate allows to add or
ios::ate Go to end-of-file on opening modify data anywhere in the
file. In both cases, file is
created if it does not exist.
ios::trunk Deletes the content of the file if
it exists.
ios::binary Binary File
ios::nocreate Open fails if the file does not
exists
ios::noreplace Open fails if the file already
exists

The different modes can be combined using the bitwise OR operator ( | ) as shown below:
fout.open(“data”,ios::app|ios::nocreate);
This opens the file in the append mode but fails to open the file if it does not exist.

Closing a File:
It is very simple. Use logical file and call close( ) method. E.g. fout.close( ); disconnects a logical
file from a physical file.

Detecting End-of-File:
Two ways:
1. while(fin){…};
An ifstream object, such as fin, returns a value of 0 if any error occurs in the file
operation including the end-of-file condition.
2. if (fin.eof( ) != 0) …
eof() is a member function of ios class. It returns non-zero value if the EOF condition is
encountered, otherwise zero.

Program to create Text File on the hard disk:


Accept student’s roll number, name and mobile number and store the data in a file called
“studdata.txt”. Roll number 0 indicates no more records to be saved in the file.

Algorithm:
1. Open the file (for writing purpose)
2. Accept roll number.
3. Repeat step no. a to c until roll number is zero.
a. Accept name and mobile no.
b. Write roll no, name and mobile no. in a file.
c. Accept another roll no.
4. Close the file.

By Darshit Shah Page 3 of 8


C++

The above algorithm is converted in the program file1.cpp.


#include <iostream.h> // cin , cout
#include <fstream.h> // ofstream
#include <conio.h> // clrscr(),getch()
#include <process.h> // exit(0)
#include <STDIO.H> // gets()
#include <iomanip.h> // setw(),setiosflags()
void main()
{
int rno;
char name[30];
char mobile[12];
ofstream outfile("studdata.txt");
if (!outfile)
{
cout << "Can not open file studdata.txt" << endl;
getch();
exit(0);
}
clrscr();
cout << "Enter Students' Information." << endl;
cout << "Enter Roll No. 0 to End." << endl;
cin >> rno;
while(rno)
{
cout << "Enter Student's Name : ";
gets(name);
cout << "Enter Student's Mobile No.:";
gets(mobile);
outfile << rno << " " << setiosflags(ios::left) << setw(30) << name
<< " " << mobile << endl;
cout << "Enter Roll No. 0 to End." << endl;
cin >> rno;
}
outfile.close();
}
File1.cpp
Here, “studdata.txt” is a physical file i.e. you will find this file on the hard disk once you run the
program while outfile is a logical file name. Once the logical file (stream) is associated with
physical file, one has to refer to the logical file name only to refer to the physical file during the
execution of whole program.
No mode is specified as outfile belongs to ofstream class and it will open file in writing mode only.
if (!outfile) checks whether we are able to open the file successfully or not.
outfile << rno << … statement transfers the data accepted via keyboard into the file. Remember,
instead of using cout, we have used outfile.
setiosflags(ios::left) sets the data to be left justified while setw(30) sets the width to 30.
Lastly, we have closed the file. Even if you don’t close the file, C++ will close the file before
leaving the program but let us do our job ourselves.

Program to read the content of the file:


Read the content of file “studdata.txt” and display all the records one by one.

Algorithm:
1. Open “studdata.txt” for reading purpose.
2. Read a record.
3. Repeat step no. a to b until end-of-file is encountered.
a. Display the record on the monitor.
b. Read another Record.
4. Close the file.

By Darshit Shah Page 4 of 8


C++
#include <iostream.h>
#include <fstream.h>
#include <conio.h>
#include <process.h>
#include <STDIO.H>

void main()
{
int rno;
char name[30];
char mobile[12];

ifstream infile("studdata.txt");
if (!infile)
{
cout << "Can not open file studdata.txt" << endl;
getch();
exit(0);
}
clrscr();
infile >> rno;
while(infile)
{
infile.getline(name,30);
infile >> mobile;
cout << rno << " " << name << " " << mobile << endl;
infile >> rno;
}
infile.close();
getch();
}
File2.cpp
Here, file “studdata.txt” is attached with stream infile. Again, infile is the object of ifstream class,
and hence we do not have to specify ios::in file mode. After successful opening of the file, we try to
read roll no. first from the file. If end-of-file is not encountered, that means a record exists in the
file and we continue reading name and mobile no. from the file within while loop. Look at two
statements of the while loop. getline() requires two arguments, first is the name of the variable
where we will store the data captured from the file and 2 nd argument is the number of characters to
be read from the file. If length exceeds 2nd argument, then getline will read only characters specified
in the 2nd argument. You can read mobile number by writing infile >> mobile as it is the last field in
the file.
That completes reading one record. Now try to read another roll no. from while loop. If EOF is
encountered, it will leave the loop.

get() and put():


C++ has provided two functions viz. get() and put() to handle a single character at a time.
The character handling functions get() and put() takes following form:
istream &get(char & ch);
ostream &put(char ch);
The get( ) reads a single character from the invoking stream and puts that value in ch. It returns a
reference to the stream. The put() writes ch to the stream and returns a reference to the stream.

Program to display the contents of any file (text file or binary file):
#include <iostream.h>
#include <fstream.h>
#include <conio.h>
#include <process.h>

By Darshit Shah Page 5 of 8


C++
void main(int argc, char * argv[]) // For accepting command line argument
{
char filename[50]="";
char ch;
ifstream infile;
clrscr();
if (argc != 2) // If user has not specified command-line arguments.
{
cout << "Command Line: readfile <filename>\n";
cout << "Enter name of the file to read its content :";
cin.getline(filename,50); // get filename from the user.
infile.open(filename, ios::in | ios:: binary); // open the file.
}
else
infile.open(argv[1], ios::in | ios:: binary); // open the file.
if (!infile)
{
cout << "Can not open file " << endl;
getch();
exit(1);
}
// File is open. Now display the content of the file on the monitor.
infile.get(ch); // Read a character from a file.
while(infile) // Repeat while loop until we reach EOF.
{
cout << ch; // Display a character on the monitor
infile.get(ch); // Read another character from the file.
}
infile.close(); // Close the file.
getch();
}
File3.cpp
The above program is self-explanatory.

Reading and Writing a Class Object:


C++ has provided two binary functions viz. read() and write() to read or write binary data. The
function write() copies a class object from memory byte by byte with no conversion. read() does
exactly opposite job. Remember, only data members are written to the disk file and not the member
function.

The function read() and write(), two binary input and output functions, takes the following form:
infile.read((char *) &V, sizeof(V));
outfile.write((char *) &V, sizeof(V));
These functions take two arguments. The first is the address of the variable V, and the second is the
length of that variable in bytes. The address of the variable must be cast to type char *.

Program to write class object into file and then display all records object-wise on the
monitor:
#include <iostream.h>
#include <conio.h>
#include <process.h>
#include <stdio.h>
#include <fstream.h>
#include <string.h>
#include <iomanip.h>

class students
{
int rno;
char name[30],mobile[12];

By Darshit Shah Page 6 of 8


C++
public:
students()
{
rno = 0;
strcpy(name,"");
strcpy(mobile,"");
}
void getdata(void)
{
cout << "Enter Roll No. : "; cin >> rno;
cout << "Enter Name : "; gets(name);
cout << "Enter Mobile No.: "; gets(mobile);
}
void display(void)
{
cout << setw(7)<< rno << " " << setw(30) <<
setiosflags(ios::left)<< name << setw(13) <<
setiosflags(ios::right)<< mobile << endl;
}
};

void main()
{
/* Open a file for storing records within it. */
fstream file("student.txt",ios::in|ios::app);
if (!file)
{
cout << "Can not open file student.txt" << endl;
getch();
exit(0);
}
// Let us get information of students from the user.
students st;
char ans;
clrscr();
do
{
st.getdata();
file.write((char *) &st, sizeof(st));
cout << "Do you want to add another Record [Y/N]";
ans = getche();
} while (ans == 'y' || ans == 'Y');

// Moves pointer to a starting position in the file.


file.seekg(0);
// Now display the contents of the file on the screen.
cout << endl << setiosflags(ios::right) <<setw(7) << "Roll No." <<
setiosflags(ios::left)<< setw(30) << "Name" << setw(14) <<
setiosflags(ios::right)<< "Mobile" << endl;
file.read((char *) & st, sizeof(st));
while(file)
{
st.display();
file.read((char *) & st, sizeof(st));
}
file.close();
getch();
}
File4.cpp
Here, we have defined class called students. getdata() accepts information of a student from the
user and display() gives its output on the monitor. The question arises, how to write data to a file?
The answer lies in function main(). The file is open for reading purpose as well as writing objects at
the end of the file. file.write() function is invoked to write data of object, byte by byte into a file.

By Darshit Shah Page 7 of 8


C++

After writing all objects, now we move pointer to the first position in a file using statement
file.seekg(0); and now we read data till we reach end-of-file. The 2nd while loop displays
information acquired from the file and stored in the object, on the monitor.

File Pointers and related Functions:


Each file has two associated file pointers known as input pointer (or get pointer) and output pointer
(or put pointer) for reading data from the file and for writing data to the file respectively. These
pointers automatically advance to next positions after related operation.
When we open a file in read-only mode, the input pointer is automatically set at the beginning of
the file. Similarly, when we open a file in write-only mode, the existing contents are deleted and the
output pointer is set at the beginning enabling us to write data from the beginning in the file. But if
we open the file for appending the data (writing new data at the end of the file), output pointer is set
to end-of-file.
Four functions can be used as under:
seekg() Moves get pointer (input) to a specified location.
seekp() Moves put pointer (output) to a specified location.
tellg() Gives the current position of the get pointer.
tellp() Gives the current position of the put pointer.

E.g.
infile.seekg(5); moves the file pointer to the byte no.5 i.e. 6th byte in a file.
infile.seekg(0); moves the file pointer to the beginning of the file.
infile.seekg(0,ios::beg); moves the file pointer to the beginning of the file.
outfile.seekg(0,ios::end); moves the file pointer at the end of the file.
outfile.seekg(m,ios::beg); moves the file pointer to (m+1)th byte in the file from beginning.
outfile.seekg(m,ios::cur); moves the file pointer by m byte in the file from current position.
outfile.seekg(-m,ios::cur); moves the file pointer backward by m byte in the file from current
position.
outfile.seekg(-m,ios::end); moves the file pointer backward by m bytes in the file from the end.

By Darshit Shah Page 8 of 8

You might also like