0% found this document useful (0 votes)
61 views

File Handling

The document discusses file handling in C++ using streams. It explains that streams are used to represent data flow and different stream classes exist for different types of data, like file streams for file input/output. It describes how files are used to store large amounts of data and file streams provide an interface between programs and files, with input streams extracting data from files and output streams writing to files. Classes like ifstream, ofstream and fstream are used for file input/output and build on classes like istream and ostream. Methods like open(), close() and get()/put() are used to work with files through file streams.

Uploaded by

Pankaj Paliwal
Copyright
© © All Rights Reserved
Available Formats
Download as PPT, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
61 views

File Handling

The document discusses file handling in C++ using streams. It explains that streams are used to represent data flow and different stream classes exist for different types of data, like file streams for file input/output. It describes how files are used to store large amounts of data and file streams provide an interface between programs and files, with input streams extracting data from files and output streams writing to files. Classes like ifstream, ofstream and fstream are used for file input/output and build on classes like istream and ostream. Methods like open(), close() and get()/put() are used to work with files through file streams.

Uploaded by

Pankaj Paliwal
Copyright
© © All Rights Reserved
Available Formats
Download as PPT, PDF, TXT or read online on Scribd
You are on page 1/ 42

File handling

Pooja Jain
Stream

 A stream is a general name given to a flow of


data. Different streams are used to represent
different kinds of data flow.
 Each stream is associated with a particular
class, which contains member functions and
definitions for dealing with that particular kind
of data flow.

August 21, 2018 Pooja Jain 2


File I/O with Streams:
 Many real-life problems handle large volumes of data,
therefore we need to use some devices such as floppy
disk or hard disk to store the data.
 The data is stored in these devices using the concept of
files. A file is a collection of related data stored in a
particular area on the disk.
 Programs can be designed to perform the read and write
operations on these files.
 A program typically involves either or both of the following
kinds of data communication:
 Data transfer between the console unit and the program.
 Data transfer between the program and a disk file.
Cont.
 The input/output system of C++ handles file operations
which are very much similar to the console input and
output operations.
 It uses file streams as an interface between the
programs and the files.
 The stream that supplies data to the program is known
as input stream and the one that receives data from the
program is known as output stream.
 In other words, the input stream extracts or reads data
from the file and the output stream inserts or writes data
to the file.
Classes for the file stream operations
 The I/O system of C++ contains a set of classes
that define the file handling methods.

 These include ifstream, ofstream and fstream.

 These classes, designed to manage the disk


files, are declared in fstream.h and therefore we
must include this file in any program that uses
files.
Details of some useful classes
Class Contents
filebuf Its purpose is to set the file buffer to read and write. Contains
openprot constant used in the open() of the filestream
classes. Also contains close() and open() as member
functions.
fstreambase Provides operations common to the file streams. Serves as a
base for fstream, ifstream and ofstream classes. Contains
open() and close() functions.
ifstream Provides input operations. Contains open() with default input
mode. Inherits the functions get(), getline(), read(), seekg()
and tellg() functions from istream.
ofstream Provides output operations. Contains open() with default
output mode. Inherits put(), seekp(), tellp(), and write()
functions from ostream.
fstream Provides support for simultaneous input and output
operations. Contains open() with default input mode. Inherits
all the functions from istream and ostream classes through
iostream.
Cont.
 C++ provides the following classes to perform output and
input of characters to/from files:
 ofstream: Stream class to write on files
 ifstream: Stream class to read from files
 fstream: Stream class to both read and write from/to files.
These classes are derived directly or indirectly from the
classes istream, and ostream.
 The ifstream, ofstream and fstream classes are declared
in the file fstream.h
 The istream and ostream classes are also included in
the fstream.h file.
Opening a file
 For opening a file, we must first create a file stream and
than link it to the filename.

 A filestream can be defined using the classes ifstream,


ofstream, and fstream that are contained in the header
file fstream.h

 A file can be opened in two ways:


 Using the constructor function of the class. This method is useful
when we open only one file in the stream.

 Using the member function open() of the class. This method is


used when we want to manage multiple files using one stream.
Opening file using constructor
 Create a file stream object to manage the stream using the
appropriate class. That is, the class ofstream is used to create
the output stream and the class ifstream to create the input
stream.
 Initialize the file object with the desired filename, e.g.:

ofstream outfile(“sample.txt”);

 The above statement creates an object outfile of class


ofstream that manages the output stream. This statement also
opens the file sample.txt and attaches it to the output stream
for writing.
 Similarly, the statement declared in as an ifstream object and
attaches to the file “sample.txt” for reading.

ifstream infile(“sample.txt”);
Single file stream working on one file

Disk
Output stream
file
outfile sample.txt
Program
Input stream

infile
Program: Writing and reading data into file, using constructors
# include <fstream.h> Opening the file sample.txt in the
void main() output mode (to write the data into it)
{
ofstream outfile(“sample.txt”); // create file for output
char ch = ‘a’;
int i = 12;
float f = 4356.15;
char arr[ ] = “hello”;
outfile << ch << endl <<i << endl << f << endl << arr; //send the data to file
outfile.close(); Closing the file, using close() method

ifstream infile(“sample.txt”); Re-opening the file sample.txt in input


mode (to read the data from it)

infile >> ch >> i >> f >> arr; // read data from file

cout << ch << i << f << arr; // send data to screen


}
ofstream

 ofstream outfile(”sample.txt”); creates an


object from this class. What we pass in the
brackets, as parameter, is actually what we
pass to the constructor. It is the name of the
file. So, to summarize: we create an object
from class ofstream, and we pass the name
of the file we want to create, as an argument
to the class’ constructor.

August 21, 2018 Pooja Jain 13


Opening file:
 ifstream OpenFile("cpp-home.txt");

 ifstream outfile;
outfile.open("cpp-home.txt");

 Difference- Just if you want to create a file handle,


but don’t want to specify the file name immediately,
you can specify it later with the function open(). And
by the way, other use of open() is for example if you
open a file, then close it, and using the same file
handle open another file. This way, you will need the
open() function.
Open() function
ifstream OpenFile(char *filename, int open_mode);
The value of open_mode defines how to be opened the file. Here is
a table of the open modes:

Parameter Meaning
ios::app Append to end of the file
ios::ate Go to end of the file on opening
ios::in Open file for reading only
ios::nocreate Open fails if the file does not exist
ios::noreplace Open fails if the file already
exists
ios::out Open file for writing only
ios::trunc Delete contents of the file if it
Cont.
 Opening a file in ios::out mode also opens it in the ios::trunc mode by
default.
 Both ios::app and ios::ate take us to the end of the file when it is
opened. But the difference between the two parameters is that the
ios::app allows us to add data to the end of the file only, while ios:: ate
mode permits us to add data or to modify the existing data anywhere in
the file.
 Creating a stream using ifstream implies input and creating a stream
using ofstream implies output. So in these cases it is not necessary to
provide the mode parameters.
 The fstream class does not provide a mode by default and thus, we
must provide the mode explicitly when using an object of fstream class.

 The mode can combine two or more parameters using the bitwise OR
operator
fstream fout ;
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 the file:
 We have specifically closed the file once writing
is over by calling the function close(). This is
necessary since we wanted to open the same
file for reading.

 We have not closed the file once reading from


file was over. This is because on termination of
the program the infile object goes out of scope.
As a result, the destructor gets called which
closes the file.
 Note: Once you have closed the file, you can’t access it anymore,
until you open it again.
Writing strings into the file:
#include<fstream.h>
void main()
{
ofstream outfile(“sample1.txt”); // Open the file in output
mode.
outfile << “The rate of change of\n”;
outfile << “momentum is directly\n;
outfile << “proportional to the force.”;
}
Reading the strings from the file

#include<fstream.h>
void main()
{
const int MAX=80;
char arr[MAX];
ifstream infile(“sample1.txt”); // Open the file in read (input) mode
while(infile) // until end of file
{
infile.getline(arr, MAX); // Reads first line from the file and stores
// it into the array arr
cout << arr; // Displaying the first line onto the console
}
}
Character i/o

 The put() and get() functions, which are


members of ostream and istream
respectively, are used to output and input a
single character at a time.
Example: To write data into the file, character by character.

void main()
{
char str[]=“C++ is superset of C. It is an object-oriented /
programming language.”;

ofstream outfile(“sample2.txt”); // Open the file in write mode

for(int i = 0; i < strlen(str); i++)


outfile.put(str[i]); // write data into the file, character by
character.
}
Example: Reading characters from the file

#include<fstream.h>
void main()
{
char ch;
ifstream infile(“sample2.txt”); // Open the same file in input mode
while(infile!= EOF)
{
inflie.get(ch); // Read the data from the file character by character
the // and store the character into the variable ch
cout << ch; // Display the character read, onto the screen
}
}
EOF
 while(!infile.eof()) or while(infile!= EOF)– The
function eof() returns a nonzero value if the end of
the file has been reached. So, we make a while
loop, that will loop until we reach the end of the file.
So, we will get through the whole file, so that we can
read it!
 infile is the object from class ifstream.This class
declares a function called get(). So, we can use this
function, as long as we have an object. The get()
function extracts a single character from the stream
and returns it.
August 21, 2018 Pooja Jain 23
Writing and reading Objects of a class
 So far we have done I/O of basic data types. Since the class objects are
the central elements of C++ programming, it is quite natural that the
language supports features for writing and reading from the disk files
objects directly.
 The binary input and output functions read() and write() are designed to
do exactly this job.
 The write() function is used to write the object of a class into the
specified file and read() function is used to read the object of the class
from the file.
 Both these functions take two arguments:
1. address of object to be written.
2. size of the object.

 The address of the object must be cast to the type pointer to char.
 One important point to remember is that only data members are written
to the disk file and the member functions are not.
Example: Writing an object into the file

class Person
{
private:
char name[40];
int age;
public:
void getData()
{
cout << “\n Enter name:”; cin >> name;
cout << “\n Enter age:”; cin >> age;
}
} ; // End of the class definition
Cont.
void main()
{
Person per ; // Define an object of Person class

per.getData(); // Enter the values to the data members of the class.

ofstream outfile(“Person.txt”); // Open the file in output mode

outfile.write((char*)&per, sizeof(per)); // Write the object into the file


}
Reading object from the file
class Student
{
private:
char name[40];
int age;
public:
void showData()
{
cout << “\n NAME = “ << name;
cout << “\n AGE = “ << age;
}
};
Cont.
void main()
{
Student studobj; // Define an object of Student class

ifstream infile(“Person.txt”); // Open the file Person.txt in read/input mode.

infile.read((char*)&studobj, sizeof(studobj)); // Read the object


// from the file Person.txt

studobj.showData(); // Display the data values on the screen


}
Example: I/O with multiple objects
class Person
{
private:
char name[40];
int age;
public:
void getData()
{
cout << “\n Enter name: :;
cin.get(name, 40);
cout << “\n Enter age: “;
cin >> age;
}
void showData()
{
cout << “\n Name =“ << name;
cout << “\n Age =“ << age;
}
} ;
Cont.
void main()
{
char ch;
Person per;
fstream file;
file.open(“Person.txt”, ios::app | ios::out | ios::in);
do
{
cout << “\n Enter person’s data: “;
per.getData();
file.write((char*)&per, sizeof(per));
cout << “\n Enter another person (y/n)?”;
cin >> ch;
}
while(ch == ‘y’);
Cont.
file.seekg(0); // reset to start of the file
file.read((char*)&per, sizeof(per)); // read the first person
while(! file.eof())
{
cout << “\n Person: “;
per.showData();
file.read((char*)& per, sizeof(per)); // read another
// person

}
} // End of the main function
File pointers and their manipulations:
 Each file has two associated pointers known as the file
pointers.

 One of them is called the input pointer or get pointer.

 Other is called the output pointer or put pointer.

 We can use these pointers to move through the files while


reading or writing.

 The input pointer is used for reading the contents of a given


file location and the output pointer is used for writing to a
given file location.
Default action

 When we open a file in read-only mode, the


input pointer is automatically set at the beginning
so that we can read the file from the start.
 Similarly, when we open a file in write-only
mode, the existing contents are deleted and the
output pointer is set at the beginning. This
enables us to write to the file from the start.
Functions for manipulation of file pointers
 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.
Cont.

infile.seekg(10);
 Moves the file pointer to the byte number 10.

 The bytes in a file are numbered beginning from


zero.

 Thus, the pointer will be pointing to the 11th byte


in the file.
Cont.

ofstream fileout;
fileout.open(“sample.txt”, ios::app);
int p = fileout.tellp();

 On execution of these statements, the output


pointer is moved to the end of the file
“sample.txt” and the value of p will represent
the number of bytes in the file.
Specifying the offset
 The seek functions seekg() and seekp() can also
be used with two arguments as follows:
seekg(offset, refposition);
seekp(offset, refposition);
 The parameter offset represents the number of
bytes the file pointer to be moved from the
location specified by the parameter refposition.
 The refposition takes one of the following these
constant defined in the ios class.
ios::beg start of the file
ios::cur current position of the pointer
ios::end end of the file.
Sample pointer offset calls and their actions.

Seek call Action


fout.seekg(0, ios::beg); go to start
fout.seekg(0, ios::cur); stay at the current position
fout.seekg(0, ios::end); go to the end of the file.
fout.seekg(m, ios::beg); move to (m+1)th byte in the file.
fout.seekg(m, ios::cur); go forward by m bytes from the
current position
fout.seekg(-m, ios::cur); go backward by m bytes from the
current position
fout.seekg(-n, ios::end); go backward by n bytes from the
end.
Example:
class Person
{
private:
char name[40];
int age;
public:
void getData()
{
cout << “\n Enter name: :;
cin.get(name, 40);
cout << “\n Enter age: “;
cin >> age;
}
} ;
Cont.
void main()
{
char ch;
Person per;
do // Write multiple objects into the file
{
cout << “\n Enter person’s data: “;
per.getData();
file.write((char*)&per, sizeof(per));
cout << “\n Enter another person (y/n)?”;
cin >> ch;
}
while(ch == ‘y’);
}
Example: This program counts the number of objects
already written into the file “Person.txt”. Then it reads the
second object and displays the values of its data members.

class person
{
private:
char name[40];
int age;
public:
void showData()
{
cout << “\n Name = “ << name;
cout << “\n Age = “ << age;
}
};
Cont.
void main()
{
person pers; // create person object
ifstream infile; // create input file
infile.open(“Person.txt”); // open the file
infile.seekg(0, ios::end); // go to end
int endposition = infile.tellg(); // find where we are
int n = endposition/sizeof(person); // number of persons
cout << “\n There are “ << n << “ persons in file: “;
cout << “\n Enter person number: “;
cin >> n;
int position = (n-1) * sizeof(person); // number times size
infile.seekg(position);
infile.read( (char*)&pers, sizeof(pers) );
pers.showData(); // display the person
}

You might also like