Vous êtes sur la page 1sur 15

Chandigarh University C++ Lecture Notes

FILE HANDLING IN C++


INTRODUCTION
Storage of data in variables and array is temporary. Such data is lost when program terminates. Files are
used for permanent storage of data. Computers store files on secondary storage devices. Ultimately, all
data items processed by computer are reduced to combinations of 0’s and 1’s. This occurs because it is
simple and economical to build electronic devices that can assume two stable states i.e. 0 and 1.

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.

 When a file is opened, a stream is associated with the file.


 Three files and their associated streams are automatically opened when program execution
begins.
1. Standard Input (associated stream is input stream)
2. Standard Output(associated stream is output stream)
3. Standard Error (associated stream is output stream)
Chandigarh University C++ Lecture Notes

 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.

INPUT AND OUTPUT WITH FILES


C++ provides the following classes to perform output and input of data to/from the files:

1. ofstream – output file stream class to write on file


2. ifstream – input file stream class to read from file
3. fstream – file stream class to read and write to/from file

HIERARCHY OF FILE STREAM CLASSES


A C++ class is a collection of data and the methods necessary to control and maintain that data. In this
lesson we will not be writing any C++ classes, but we will learn to use a few, such as stream classes.

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:

 istream is a general purpose input stream. cin is an example of an istream.


 ostream is a general purpose output stream. cout and cerr are both examples of ostreams.
 ifstream is an input file stream. It is a special kind of an istream that reads in data from a data file.
 ofstream is an output file stream. It is a special kind of ostream that writes data out to a data file.

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

FUNCTIONS IN FILE HANDLING


open( ) To create a file
close( ) To close an existing file
get( ) To read single character from a file
put( ) To write single character to a file
read( ) To read data from file
write( ) To write data to file

OPERATIONS TO BE PERFORMED ON FILE


1. Opening/Defining a file
2. Closing a file
3. Writing to a file
4. Reading from file

1. DEFINING AND OPENING A FILE


The first operation generally performed on an object of one of these classes is to associate it to a real file.
This procedure is known as to open a file.

We can open a file in 2 ways:


Chandigarh University C++ Lecture Notes

 Using constructor function


 Using open( ) function

Syntax for using constructor function is:

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;

stream_object.open(“filename”); //using open function

Example:

fstream f1; //creating stream object of type fstream class


f1.open(“file1”); //connect stream to a file

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.

PROGRAM 1: WAP to write a set of lines to a specified file.


#include<fstream>
using namespace std;
int main()
{
ofstream f1;
f1.open("file1.txt");
f1<<"Hello, this is a sample program:\n";
f1<<"to write a set of lines to a file.\n";
f1<<"****WRITING TO A FILE****";
f1.close();
return 0;
Chandigarh University C++ Lecture Notes

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

FILE OPENING MODES IN C++


ios::app Append mode. All output to that file to be appended to the end of file.

ios::ate (At end) Open a file for output and move the read/write control to the end of the file.

ios::in Open a file for reading only.

ios::out Open a file for writing only.

ios::trunc If the file already exists, its contents will be truncated/deleted before opening the file.

ios::binary Open a file in binary mode. Default mode is text.


ios:: nocreate Open fails if file does not exist

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

ifstream f1; //creating object for reading the contents of file


char fname[10];
char ch;
cout<<"enter a file name..";
cin>>fname;
f1.open(fname); // opening the file using open( ) function and connecting it to the stream
if(f1.fail())
{
cerr<<"No such file
exists..\n"; exit(1);
}
while(!f1.eof())
{
ch=(char)f1.get(); //get function returns the end of file
cout.put(ch);

}
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.

RANDOM ACCESS TO FILES:


The file pointer

 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.

The seekg(), seekp(), tellg() and tellp() Functions

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 seekg() member function takes two arguments:


• Number of bytes to move.
• Reference in the file from which the pointer has to be repositioned.
For example:
ifstream iFi1;
iFi1.seekg(10,ios:beg)
;
means, “position the get pointer 10 bytes from the beginning of the 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

• ios:end – the end of the file

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";

cout<<"Enter new details.\n";


char nam[20]=" ", br[3]=" ";
float mks;
cout<<"New name:(Enter '.' to retain old one): ";
cin>>nam;
cout<<"New branch:(Press '.' to retain old one): ";
cin>>br;
cout<<"New marks:(Press -1 to retain old one): ";
cin>>mks;

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();

fstream fio("marks.dat", ios::in | ios::out);


char ans='y';
while(ans=='y' || ans=='Y')
{
stud1.getdata();
fio.write((char *)&stud1, sizeof(stud1));
cout<<"Record added to the file\n";
cout<<"\nWant to enter more ? (y/n)..";
cin>>ans;
}
Chandigarh University C++ Lecture Notes

clrscr();
int rno;
long pos;
char found='f';

cout<<"Enter rollno of student whose record is to be modified: ";


cin>>rno;

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();

ifstream f1; //opening file for reading purpose


f1.open("file.txt",ios::in);
if(!f1)
{
cout<<"Unable to process your file due to following reasons:\n";
cout<<"1. File doesn't exist.\n";
cout<<"2. the path you specifies is incorrect.\n";
return 1;
}
cout<<"After opening, file position
is:"<<f1.tellg()<<endl; char ch;
while(!f1.eof())
{
cout<<"At
position:"<<f1.tellg(); f1>>ch;
cout<<"Character \""<<ch<<"\""<<endl;
}
f1.close();
return 0;
}
Output:
Current position in file is:26
After opening, file position
is:0 At position: 0 Character
"A"
At position: 1 Character
"B" At position: 2
Character "C"
Chandigarh University C++ Lecture Notes

At position: 3 Character "D"


At position: 4 Character "E"
At position: 5 Character "F"
At position: 6 Character "G"
At position: 7 Character "H"
At position: 8 Character "I"
At position: 9 Character "J"
At position: 10 Character "K"
At position: 11 Character "L"
At position: 12 Character
"M" At position: 13
Character "N" At position: 14
Character "O" At position: 15
Character "P" At position: 16
Character "Q" At position: 17
Character "R" At position: 18
Character "S" At position: 19
Character "T" At position: 20
Character "U" At position: 21
Character "V" At position: 22
Character "W" At position:
23 Character "X" At position:
24 Character "Y" At position:
25 Character "Z" At position:
26 Character "Z"

Links for reference:


https://www.tutorialspoint.com/cplusplus/cpp_files_streams.htm
http://www.cplusplus.com/doc/tutorial/files/
https://www.codesdope.com/cpp-file-io/

Vous aimerez peut-être aussi