Professional Documents
Culture Documents
CHAPTER 11: Working With Files: File Field1 Field2
CHAPTER 11: Working With Files: File Field1 Field2
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
Records E.O.F.
Field Field Field
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.
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).
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.
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.
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.
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.
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.
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>
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];
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');
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.
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.