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

oops5

Object Oriented Programming
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
14 views

oops5

Object Oriented Programming
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 71

UNIT IV

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:

• It is difficult to read huge amount of data from keyboard.


•Data entered from keyboard is volatile i.e., that data is cleared
when power goes off.

Files help store these data permanently on a storage device. The


term “Data” is commonly referred to as known facts or
information.
Why files are needed?
When a program is terminated, the entire data is lost. Storing in a
file will preserve your data even if the program terminates.

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:-

istream stands for input stream.


This class is derived from the class ‘ios’.
This class handle input stream.

The extraction operator(>>) is overloaded in this class to handle


input streams from files to the program execution.
This class declares input functions such as get(), getline() and
read().
3. ostream:-
ostream stands for output stream.
This class is derived from the class ‘ios’.
This class handle output stream.
The insertion operator(<<) is overloaded in this class to handle
output streams to files from the program execution.
This class declares output functions such as put() and write().

4. streambuf:-
This class contains a pointer which points to the buffer which is
used to manage the input and output streams.
5. fstreambase:-

This class provides operations common to the file


streams. Serves as a base for fstream, ifstream and
ofstream class.
This class contains open() and close() function.

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.

void open(const char *filename, ios::openmode mode);

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

C++ provides functions to move file pointers within a file.

a)seekg() and seekp()


b) tellg() and tellp()
What is a file pointer?
A pointer is used to handle and keep track of the
files being accessed. Every file maintains two
pointers called get_pointer (in input mode file) and
put_pointer (in output mode file), which tells the
current position where reading or writing will take
place with the use of opening modes and their
respective manipulators.
A file position pointer points to a particular index in a file where read or write
operations occur. There are two types of pointers get and put. We can find
the position of these pointers by associated functions tellg() and tellp(). Also,
we can seek(change) the position of the pointer with the
function seekg() and seekp(). There, we can either read or write after seeking
a particular position. Methods like seekg(), seekp() takes parameters as long
integers and seek directions.
A few examples are :
ios::beg (for positioning at the beginning of a stream)
ios::cur (for positioning relative to the current position of a stream)
ios::end (to position relative to the end of a stream)
a) seekg() and seekp()
These functions move the file pointer (i.e., the "get" pointer for input
or the "put" pointer for output).
seekg(): Move the input file pointer (get pointer) to a specific
location.
seekp(): Move the output file pointer (put pointer) to a specific
location.

b) tellp() & tellg()


tellp(): returns the current position of put pointer, which is used with
output streams while writing the data to the file.
tellg():returns the current position of get pointer which is used with
input streams while receiving the data from the file.
Both functions accept two parameters:
The offset value (in bytes).
The reference position, which can be:
std::ios::beg: Beginning of the file.
std::ios::cur: Current position of the pointer.
std::ios::end: End of the file.
#include <fstream>
#include <iostream>
int main() {
std::ifstream inputFile("example.txt", std::ios::binary); // Open in binary mode

inputFile.seekg(10, std::ios::beg); // Move the file pointer to the 10th


byte from the beginning
inputFile.seekg(5, std::ios::cur); // Move the pointer 5 bytes forward
from the current position
inputFile.seekg(0, std::ios::end); // Move the pointer to the end of the file
inputFile.close();
return 0;
}
#include <fstream>
#include <iostream>

int main() {
std::ifstream inputFile("example.txt", std::ios::binary); // Open in binary
mode

inputFile.seekg(0, std::ios::end); // Move to the end of the file


std::streampos fileSize = inputFile.tellg(); // Get the size of the file

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

Manipulators are helping functions that can modify


the input/output stream. It does not mean that we
change the value of a variable, it only modifies the I/O
stream using insertion (<<) and extraction (>>)
operators.
Types of Manipulators
There are various types of manipulators:

Manipulators without arguments: The most important


manipulators defined by the IOStream library are provided
below.

endl: It is defined in ostream. It is used to enter a new line and


after entering a new line it flushes (i.e. it forces all the output
written on the screen or in the file) the output stream.
ws: It is defined in istream and is used to ignore the whitespaces in
the string sequence.

ends: It is also defined in ostream and it inserts a null character into


the output stream. It typically works with std::ostrstream, when the
associated output buffer needs to be null-terminated to be processed
as a C string.

flush: It is also defined in ostream and it flushes the output stream,


i.e. it forces all the output written on the screen or in the file. Without
flush, the output would be the same, but may not appear in real-time.
•A binary file is a computer file that uses the binary number
system to encode information. The file format specification for a
binary file defines the binary sequence of bytes to be stored in
the file, and does not require an encoding scheme for the file's
text content.
• binary refers to:
–Binary File: A file that does not contain human-readable text
–Executable: A binary file containing computer code
–Binary code: Data and text represented digitally.
•How is a binary file used?
Binary files are used to store data and used in
programming.
The term "binary" refers to the file containing a
sequence of 1s and 0s rather than letters or numbers
like ASCII text.
Binary files are usually created by compilers,
translating source code into a machine-readable
format that computers can understand.
Binary functions
Binary functions are special functions that only accept binary
data as input and return binary data as output. The main
functions of binary are:
–Create: Create a new binary file with the given contents.
–Write: Write data to an existing file.
–Read: Read data from an existing file. The data is returned
as an array containing the raw bytes of each line in the file
(each line is separated by a newline character 'n').
•When are binary file formats useful?
•Binary file formats are most useful for storing raw data
that isn’t intended to be interpreted by humans. This
includes things like bitmaps, audio files, and video
streams.
•Binary formats are also useful when storing large amounts
of data in a small space. This is especially true of image
formats like JPEG and PNG, which compress the image
into an efficient format that can still be decompressed
on-the-fly by your computer.
Common problems with binary files

•Difficult to manipulate: A binary file contains only 0s and 1s; if you


want to change one bit in the file, you must also change all other bits.
This makes it difficult to edit or manipulate a binary file without
damaging its contents.

•Inconsistent efficiency: Binary files usually have a fixed size;


efficiency isn't always uniform across the entire file — some parts may
be larger than others. This can make it difficult to read large amounts
of information quickly from a binary file without slowing down your
program's performance.
•What is Binary File Handling
•Binary File Handling is a process in which we create a
file and store data in its original format. It means that if
we stored an integer value in a binary file, the value will
be treated as an integer rather than text.

•Binary files are mainly used for storing records just as we


store records in a database. It makes it easier to access or
modify the records easily.
Binary file operation modes
•ios::binary | ios::in
This mode is used to open a file in binary mode for reading.
The file pointer is placed at the beginning of the file. It is the
default mode when a file is opened without any specified
mode.
•ios::binary | ios::out
This mode is used to open a file in binary mode for writing. If
the file does not exist, it will be created. If the file already
exists, it will be overwritten. The file pointer is placed at the
beginning of the file
•ios::binary | ios::app
This mode is used to open a file in binary mode for
appending. If the file does not exist, it will be created. If
the file already exists, all new data will be added to the
end of the file.

•ios::binary | ios::in | ios::out


This mode is used to open a file in binary mode for both
reading and writing. The file pointer is placed at the
beginning of the file.
•ios::binary | ios::in | ios::out | ios::trunc
This mode is used to open a file in binary mode for both
reading and writing, and truncates the file to zero length if
it already exists. The file pointer is placed at the
beginning of the file.

•ios::binary | ios::in | ios::out | ios::app


This mode is used to open a file in binary mode for both
reading and writing, and all new data will be added to the
end of the file.
•write() Syntax
write((char*) data_address, data_size);

•(char*): Type cast the data to be written in the file as an


array of characters.
•data_address: Points to the memory address of the data
items to be written in a binary file.
•data_size: It specifies the number of bytes of the data item
to be written in a binary file.
• Testing for errors, either check error state bits or use methods like
good(), fail() etc.
• A special method is_open() can be used to check whether opening file
is successful or not. Method is_open() returns true if open is
successful
• For all other i/o operations, error can be checked using one of the
following:
• Method good() returns true if operation is successful. None of the
bits/flags is set in error state.
• Method fail() returns true when operation is unsuccessful, i.e. if failbit
or badbit is set.
• Method eof() returns true when end of file is reached, i.e. if eofbit is
set.
• Operator ! returns true when operation is unsuccessful, like fail()
• Stream pointer is null when operation is unsuccessful Examples:
• if (fobj.is_open()) {//file opened, process} else {//error}
• if (fobj.good()) {//successful operation, process} else {//error}
• If (fobj.fail()) {//error} else {// successful operation, process}
• If (fobj.bad()) {//error} else {// successful operation, process}
• If (fobj.eof()) {//error, end of file} else {// process}
• If (!fobj) {//error} else {// successful operation, process}
• if (fobj) {// successful operation, process} else {//error}
• Program to copy contents of one file to another file
using get() and put() methods
• // copy one file to another using get(), put()
• // character by character copy
• int main()
• {
• ifstream fin;
• fin.open(“file1.pdf”, ios::in | ios::binary);
• ofstream fout;
• fout.open(“file2.pdf”, ios::out | ios::binary);
• if (! (fin.is_open() && fout.is_open()))
• { cout << “Error opening file…”, exit(1); }
• char ch;
• while(!fin.eof())
• { ch = fin.get(); fout.put(ch); }
• fin.close();
• fout.close();
• return 0;
• }
• What is a File?
A file is named a collection of related information that is recorded on
secondary storage such as magnetic disksA file is named a
collection of related information that is recorded on secondary
storage such as magnetic disks, magnetic tapes,A file is named a
collection of related information that is recorded on secondary
storage such as magnetic disks, magnetic tapes, and optical disks.

• What is File Organization?


File Organization refers to the logical relationships among various
records that constitute the file, particularly with respect to the
means of identification and access to any specific record. In
simple terms, Storing the files in a certain order is called File
The Objective of File Organization
• It helps in the faster selection of records i.e. it makes the
process faster.
• Different Operations like inserting, deleting, and updating
different records are faster and easier.
• It prevents us from inserting duplicate records via various
operations.
• It helps in storing the records or the data very efficiently
at a minimal cost.
Pile file method
• It is a standard method for sequential file
organization in which the data elements are
inserted one after another in the order those are
inserted. And in case of a new record being
inserted, it is placed at the end position of the
file that is after the last inserted data element or
record.
2. Sorted file method
The Sorted file method is another popular method
for it in the database management system. This
method provisions the data element to be arranged
and stored in the sorted order. The data elements
are stored as ascending or descending order based
upon the primary key or any other key reference.
• Advantages
• The sequential file organization is efficient and process faster
for the large volume of data.
• It is a simple file organization compared to other available file
organization methods.
• This method can be implemented using cheaper storage
devices such as magnetic tapes.
• It requires fewer efforts to store and maintain data elements.
• The sequential file organization technique is useful for report
generation and statistical computation process.
Disadvantages
• The sorting operation is a time-consuming process and
more memory space for the sorted file method in the
sequential file organization.
• The sorting operations iterate for every writes operation
such as insert, update, or delete
• The traversing time is high in the sequential file
organization as for each writes operation, the system or
the program control cannot find a particular data item
directly at one go, it has to traverse through the sequence
of data items.
Direct Access File organization :
Direct access file is also known as random access or relative file organization.
• In direct access file,all records are stored in direct access
storage device (DASD), such as hard disk. The records are randomly
placed throughout the file.
• The records does not need to be in sequence because they
are updated directly and rewritten back in the same location.
• This file organization is useful for immediate access to large
amount of information. It is used in accessing large databases.

• It is also called as hashing.


• It allows us to access data directly from any location within the file, without the
need to read or write all the records that come before it. Furthermore, this method
accesses records within the file by using their physical addresses or positions.
• Direct file access is best suited for applications that require quick and efficient access
to specific records or data elements within a file.

• For example, in a database application, we may need to quickly retrieve


customer data based on a specific customer ID. Direct file access can quickly access the
record containing the customer data without having to read through all the records
that come before it.
• Direct Access File organization :
Advantages of direct access file organization
1.Direct access file helps in online transaction processing system (OLTP) like online
railway reservation system.
2.In direct access file, sorting of the records are not required.
3.It accesses the desired records immediately.
4.It updates several files quickly.
5.It has better control over record allocation.

Disadvantages of direct access file organization


• Direct access file does not provide back up facility.
1. It is expensive.
2.It has less storage space as compared to sequential file.
Indexed File Organization :
• Indexed sequential access file combines bothsequential file and direct
access file organization.
• In indexed sequential access file, records are stored randomly on a

direct access device such as magnetic disk by a primary key.

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

2.Offers Faster search and retrieval of data to users.


3.Indexing also helps you to reduce tablespace as you don’t need to link to
a row in a table, as there is no need to store the ROWID in the Index.
Thus you will able to reduce the tablespace.
4.You can’t sort data in the lead nodes as the value of the primary key
classifies it.
Disadvantages of Indexing :
Important drawbacks/cons of Indexing are:
1.To perform the indexing database management system, you need
a primary key on the table with a unique value.
2.You can’t perform any other indexes in Database on the Indexed data.

3.You are not allowed to partition an index-organized table.


4.SQL Indexing Decrease performance in INSERT, DELETE, and UPDATE
query.
Thank you

You might also like

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy