Académique Documents
Professionnel Documents
Culture Documents
RECORD: A record is composed of several fields. For example, a record for a particular employee might
consists of following fields..
Employee ID
Name
Address
Monthly salary
Amount of federal taxes withheld.
Thus, a record is a group of related fields. Ofcourse, a particular company may have many employees and
will have this record for each employee.
FILE: A file is a group of related records. To retrieve the specific record from a file, atleast one field in
each record is chosen as record key. A record key identifies a record as belonging to a particular person or
entity. Here, employee ID can be selected as record key.
FILES AND STREAMS: File is simply a sequential stream of bytes. Each file ends with eof (end of file)
marker. Stream provides the communication channel (or we can say communication link) between files
and programs.
Standard Input stream enables a program to read data from keyboard. Example, cin object of class
istream.
Standard output stream enables a program to print data on the screen. Example, cout object of
class ostream.
A class is a data type, analogous to ints, floats, and doubles. A C++ object is a specific variable having a
class as its data type. cin and cout are special pre-specified objects with different classes as their data
types.
A C++ stream is a flow of data into or out of a program, such as the data written to cout or read from cin.
For this class we are currently interested in four different classes:
Object Oriented Programming (e.g. C++) makes heavy use of a concept called inheritance, in which some
classes inherit the properties of previously written classes. The descendant classes then add on additional
properties, making them specializations of their parent class.
For example, in the diagram below of (a portion of) the stream class hierarchy, we see that ifstream is a
specialization of istream. What this means is that an ifstream IS an istream, and includes all the properties
of the istream class, plus some additional properties of its own.
Chandigarh University C++ Lecture Notes
filestream_class stream_object(“filename.txt”);
example:
ofstream f1(“abc.txt”); //open( ) function will be called implicitly by the compiler
An open file is represented within a program by a stream and any input or output operation performed on
this stream object will be applied to the physical file associated to it. Function open( ) can be used to open
a file.
Syntax:
filestream_class stream_object;
Example:
Just like we use cout and cin objects of class iostream to read and write a program to console I/O. Same
way, we need to create an object of file stream to read from and write to file.
This text file will be created in the directory in which you have saved your program.
PROGRAM 2: WAP to write a set of lines to a user defined file where name of file is
specified by user.
#include<fstream>
#include<iostream>
using namespace std;
int main()
{
ofstream f1;
char fname[10];
cout<<"Enter the file name you want to create/open: ";
cin>>fname;
f1.open(fname);
f1<<"Hello, this is a sample program 2:\n";
f1<<"to write a set of lines to a user defined file.\n";
f1<<"****WRITING TO A FILE****";
f1.close();
return 0;
}
Chandigarh University C++ Lecture Notes
ios::ate (At end) Open a file for output and move the read/write control to the end of the file.
ios::trunc If the file already exists, its contents will be truncated/deleted before opening the file.
PROGRAM 3: WAP to read a text file and display its contents on the screen.
#include<fstream>
#include<iostream>
using namespace std;
int main()
{
Chandigarh University C++ Lecture Notes
}
f1.close();
return 0;
}
YOU CAN OPEN MULTIPLE FILES WITH SINGLE STREAM OBJECT BUT MAKE SURE TO
CLOSE THE FIRST FILE BEFORE OPENING THE SECOND FILE.
Chandigarh University C++ Lecture Notes
fail( ) stream function is used to check whether a file has been opened for input or output successfully. If
file opening operation fails, then fail( ) returns a non-zero character.
eof( ) stream function is used to check whether the file pointer has reached the end of a file character or
not. If successful, it returns a nonzero otherwise returns 1.
Each file stream class contains a file pointer that is used to keep track of the current read/write
position within the file.
When something is read from or written to a file, the reading/writing happens at the file pointer’s
current location.
By default, when opening a file for reading or writing, the file pointer is set to the beginning of
the file.
However, if a file is opened in append mode, the file pointer is moved to the end of the file, so
that writing does not overwrite any of the current contents of the file.
In c++ we have get pointr and put pointer for getting(reading) data from file and putting (writing
) data on the file respectively.
Random file access with seekg() and
seekp()
So far, all of the file access we’ve done has been sequential -- that is, we’ve read or written the
file contents in order.
However, it is also possible to do random file access -- that is, skip around to various points in the
file to read its contents.
This can be useful when your file is full of records, and you wish to retrieve a specific record.
Rather than reading all of the records until you get to the one you want, you can skip directly to
the record you wish to retrieve.
Random file access is done by manipulating the file pointer using the seekg() function (for input)
and seekp() function (for output). In case you are wondering, the g stands for “get” and the p for
“put”.
The seekg() and seekp() functions take two parameters. seekg() method actually moves the file pointer.
The first parameter is an offset that determines how many bytes to move the file pointer. The second
parameter is an ios flag that specifies what the offset parameter should be offset from.
tellg() tells the position of get pointer. And tellp() gets the position of put pointer
Every file maintains two pointers called get_pointer (in input mode file) and put_pointer (in
output mode file) which tells the current position in the file where reading or writing will takes
place. (A file pointer in this context is not like a C++ pointer but it works like a book-mark in a
book.). These pointers help attain random access in file. That means moving directly to any
location in the file instead of moving through it sequentially.
There may be situations where random access in the best choice. For example, if you have to
modify a value in record no 21, then using random access techniques, you can place the file
Chandigarh University C++ Lecture Notes
pointer at the beginning of record 21 and then straight-way process the record. If sequential
access is used, then you'll have to unnecessarily go through first twenty records in order to reach a
record 21.
In C++, random access is achieved by manipulating seekg(), seekp(), tellg() and tellp() functions.
The seekg() and tellg() functions allow you to set and examine the get_pointer, and the seekp()
and tellp() functions perform these operations on the put_pointer.
The seekg() and tellg() functions are for input streams (ifstream) and seekp() and tellp() functions
are for output streams (ofstream). However, if you use them with an fstream object then tellg()
and tellp() return the same value. Also seekg() and seekp() work the same way in an fstream
object.
The working of seekg() & seekp() and tellg() & tellp() is just the same except that seekg() and
tellg() work for ifstream objects and seekp() and tellp() work for ofstream objects.
All the iostream class objects can be repositioned by using either the seekg() or the seekp()
member function. These functions move the get and put pointers respectively to an absolute
address within the file or to a certain number of bytes from a particular position.
The tellg() and tellp() functions can be used to find out the current position of the get and put file
pointers respectively in a file.
The first argument is an integer that specifies the number of bytes positions(also called offset).
The second argument is the reference point. There are three reference points defined in the ios
class:
• ios:beg – the beginning of the file.
• ios:cur – the current position of the file pointer
Chandigarh University C++ Lecture Notes
Example demonstrating the concept of file pointer and random access in C++.
#include<fstream.h>
#include<conio.h>
#include<stdlib.h>
#include<stdio.h>
#include<string.h>
class student
{
int rollno;
char name[20];
char branch[3];
float marks;
char grade;
public:
void getdata()
{
cout<<"Rollno: ";
cin>>rollno;
cout<<"Name: ";
cin>>name;
cout<<"Branch: ";
cin>>branch;
cout<<"Marks: ";
cin>>marks;
if(marks>=75)
{
grade = 'A';
}
else if(marks>=60)
{
grade = 'B';
}
else if(marks>=50)
{
grade = 'C';
}
Chandigarh University C++ Lecture Notes
else if(marks>=40)
{
grade = 'D';
}
else
{
grade = 'F';
}
}
void putdata()
{
cout<<"Rollno: "<<rollno<<"\tName:
"<<name<<"\n"; cout<<"Marks:
"<<marks<<"\tGrade: "<<grade<<"\n";
}
int getrno()
{
return rollno;
}
void modify();
}stud1, stud;
void student::modify()
{
cout<<"Rollno: "<<rollno<<"\n";
cout<<"Name: "<<name<<"\tBranch: "<<branch<<"\tMarks: "<<marks<<"\n";
if(strcmp(nam, ".")!=0)
{
strcpy(name, nam);
}
if(strcmp(br, ".")!=0)
Chandigarh University C++ Lecture Notes
{
strcpy(branch, br);
}
if(mks != -1)
{
marks = mks;
if(marks>=75
)
{
grade = 'A';
}
else if(marks>=60)
{
grade = 'B';
}
else if(marks>=50)
{
grade = 'C';
}
else if(marks>=40)
{
grade = 'D';
}
else
{
grade = 'F';
}
}
}
void main()
{
clrscr();
clrscr();
int rno;
long pos;
char found='f';
fio.seekg(0);
while(!fio.eof()
)
{
pos = fio.tellg();
fio.read((char *)&stud1, sizeof(stud1));
if(stud1.getrno() == rno)
{
stud1.modify();
fio.seekg(pos);
fio.write((char *)&stud1, sizeof(stud1));
found = 't';
break;
}
}
if(found=='f')
{
cout<<"\nRecord not found in the file..!!\n";
cout<<"Press any key to exit...\n";
getch();
exit(2);
}
fio.seekg(0);
cout<<"Now the file contains:\n";
while(!fio.eof())
{
fio.read((char *)&stud, sizeof(stud));
stud.putdata();
}
fio.close();
getch();
}
Chandigarh University C++ Lecture Notes
#include<iostream>
#include<fstream>
using namespace std;
int main()
{
ofstream f2;
f2.open("file.txt",ios::out);
if(!f2)
{
cout<<"Error in creating a
file!!"; return 1;
}
f2<<"ABCDEFGHIJKLMNOPQRSTUVWXYZ"; //writing
data to file cout<<"Current position in file
is:"<<f2.tellp()<<endl;
f2.close();