oops5
oops5
File Handling
Classes for file stream operation,
Opening and closing a file,
File pointers and their manipulation,
File operations on binary files – variables,
class objects,
sequential file organization,
Direct access files.
Case Study: Write a program in c++ to create a
database for airline reservation system using file
handling.
A file is a collection of related data stored on a disk. It is
advantageous to work with data stored in files rather than
working with data given from keyboard due to following
reasons:
If you have to enter a large number of data, it will take a lot of time
to enter them all.
However, if you have a file containing all the data, you can easily
access the contents of the file using a few commands.
You can easily move your data from one computer to another
without any changes.
Types of Files
When dealing with files, there are two types of files you should know about:
Text files
Binary files
1. Text files
Text files are the normal .txt files. You can easily create text files using
any simple text editors such as Notepad.
When you open those files, you'll see all the contents within the file as
plain text. You can easily edit or delete the contents.
They take minimum effort to maintain, are easily readable, and provide
the least security and takes bigger storage space.
2. Binary files
Binary files are mostly the .bin files in your computer.
Instead of storing data in plain text, they store it in the binary form (0's
and 1's).They can hold a higher amount of data, are not readable easily,
and provides better security than text files.
File Operations in C++
C++ provides us with four different operations for file handling.
They are:
open() – This is used to create a file.
read() – This is used to read the data from the file.
write() – This is used to write new data to file.
close() – This is used to close the file.
File handling :
In C++ programming we are using the iostream standard library, it
provides cin and cout methods for reading from input and writing to
output respectively.
File handling in C++ involves working with files to read from and
write data to them. C++ provides a set of libraries to handle these
tasks, mainly through classes like ifstream, ofstream, and fstream,
which are included in the <fstream> header file.
Example:
#include<iostream>
#include<fstream>
ofstream:
This class helps create and write the data to the file obtained from the
program’s output. It is also known as the output stream.
ifstream:
We use this class to read data from files and also known as the input
stream.
fstream:
This class is the combination of both ofstream and ifstream. It provides
the capability of creating, writing and reading a file.
To access the following classes, you must include the fstream as a
header file like how we declare iostream in the header.
The I/O system of C++ contains a set of classes which define the file
handling methods. These include ifstream, ofstream and fstream
classes. These classes are derived from fstream and from the
corresponding iostream class. These classes, designed to manage the
disk files, are declared in fstream and therefore we must include this
file in any program that uses files.
1. ios:-
ios stands for input output stream.
This class is the base class for other classes in this class hierarchy.
This class contains the necessary facilities that are used by all the
other derived classes for input and output operations.
2. istream:-
4. streambuf:-
This class contains a pointer which points to the buffer which is
used to manage the input and output streams.
5. fstreambase:-
6. ifstream:-
This class provides input operations.
It contains open() function with default input mode.
Inherits the functions get(), getline(), read(), seekg() and
tellg() functions from the istream.
7. ofstream:-
This class provides output operations. It contains open() function
with default output mode. Inherits the functions put(), write(),
seekp() and tellp() functions from the ostream.
8. fstream:-
This class provides support for simultaneous input and output
operations. Inherits all the functions from istream and ostream classes
through iostream.
9. filebuf:-
Its purpose is to set the file buffers to read and write. We can also use
file buffer member function to determine the length of the file.
In C++, files are mainly dealt by using three classes
fstream, ifstream, ofstream available in fstream headerfile.
Type Description
It is used to create files, write information
fstream
to files, and read information from files.
ifstream It is used to read information from files.
It is used to create files and write
ofstream
information to the files.
Mode – There different mode to open a file and it explained in this article.
Mode Description
ios::in File opened in reading mode
ios::out File opened in write mode
ios::app File opened in append mode
File opened in append mode but read and write performed
ios::ate
at the end of the file.
ios::binary File opened in binary mode
ios::trunc -(truncate) discard the files’ contents if it exists
Step in file handling
1. Declare a object of ifstream / ofstream /
fstream class
2. Open file in desired mode
3. Perform required operations on the file
4. Close the file
Opening a File
A file must be opened before you can read from it or write to it.
Either ofstream or fstream object may be used to open a file for
writing. And ifstream object is used to open a file for reading purpose
only.
Following is the standard syntax for open() function, which is a
member of fstream, ifstream, and ofstream objects.
Here, the first argument specifies the name and location of the file to
be opened and the second argument of the open() member function
defines the mode in which the file should be opened.
Program for Opening File:
#include <iostream> // Include the input/output stream library
using namespace std;
#include <fstream> // Include the file stream library
int main(){
fstream f;
f.open("File_Name", ios::out);
if (!f){
cout<<"Error while creating the file";
}
else{
cout<<"File created successfully";
f.close();
}
return 0;
}
Explanation of above code
•Here we have an iostream library, which is responsible for
input/output stream.
•We also have a fstream library, which is responsible for handling
files.
•Creating an object of the fstream class and named it as ‘FileName’.
•On the above-created object, we have to apply the open() function to
create a new file, and the mode is set to ‘out’ which will allow us to
write into the file.
•We use the ‘if’ statement to check for the file creation.
•Prints the message to console if the file doesn’t exist.
•Prints the message to console if the file exists/created.
•We use the close() function on the object to close the file.
Program for Writing to File:
int main() {
fstream f;
f.open("FileName.txt", ios::out);
if (!f) {
cout<<" Error while creating the file ";
}
else {
cout<<"File created and data got written to file";
FileName<<“welcome ";
FileName.close();
}
return 0; }
Reading from file in
•Creating C++ variable with the named x.
a character
int main() {
•Iterating of the file with the help of while loop.
fstream f;
f.open("FileName.txt", ios::in); •Getting the file data to the variable x.
if (!f {
•Here we are using if condition with eof() which
cout<<"File doesn’t exist.";
} stands for the end of the file to tell the compiler to
else {
read till the file’s end.
char x;
while (1) { •We use the ‘break’ statement to stop the reading
FileName>>x;
from file when it reaches the end.
if(FileName.eof())
break; •The cout statement to print the content that is
cout<<x;
available in the variable x.
}
} •We use the close() function on the object to close
FileName.close();
the file
return 0;
Read the contents(data) from the file
#include<iostream.h> while(!infile.eof())
#include<fstream.h> {
void main() ch=infile.get();
{ cout<<ch;
ifstream infile; }
char ch; infile.close();
infile.open(“fname.txt”, ios::in); }
if(!infile)
{
cout<<"file does not exist";
exit(1);
}
File Pointer Manipulation
int main() {
std::ifstream inputFile("example.txt", std::ios::binary); // Open in binary
mode
std::cout << "Size of the file: " << fileSize << " bytes." << std::endl;
inputFile.close();
return 0;
}
int main ()
{
ofstream file;
file.open ("myfile.txt", ios::out); // Open file in write mode.
cout <<"Position of put pointer before writing:" <<file.tellp () << endl;
file << "Hello Everyone"; // Write on file.
cout <<"Position of put pointer after writing:" <<file.tellp () << endl;
file.close ();
ifstream file1;
file1.open ("myfile.txt", ios::in); // Open file in read mode.
cout <<"Position of get pointer before reading:"<< file1.tellg() << endl;
int iter = 5;
while(iter--){
char ch;
file1 >> ch; // Read from file.
cout<<ch;
}
cout<< endl << "Position of get pointer after reading:"<<file1.tellg();
file1.close ();
}
Explanation:
Before writing anything to the file, it was opened in the out mode; hence the
put pointer was at 0.
After writing the string Hello Everyone, the put pointer will reach to end of
the file, which is 14.
For reading, the get pointer is used, and the initial position of get pointer is 0.
After reading five characters from the file, the get pointer reaches 5.
Manipulators
• This file have multiple keys. These keys can be alphanumeric in which the records
are ordered is called primary key.
• The data can be access either sequentially or randomly using the index. The index is
stored in a file and read into memory when the file is opened
• Indexed File Organization :
Indexed file access is a method that incorporates the benefits of
both sequential and direct file access. This method involves creating
an index file that maps logical keys or data elements to their
corresponding physical addresses within the file. Moreover, the
system stores the index separately from the data file, enabling quick
access to locate the desired data.
Indexed file access is best suited for applications that require fast access
to particular data elements within a large file. For example, in a file
system, we may need to access specific files based on their name or
location. The index created for the file system allows quick access to
the file’s physical location, enabling efficient access.
• Indexed File Organization :
Advantages of Indexing
Important pros/ advantage of Indexing are:
1.It helps you to reduce the total number of I/O operations needed to retrieve
that data, so you don’t need to access a row in the database from an index
structure.