Lecturer Notes BCA Pt-II - OOPs Unit-V File Management-I

Download as pdf or txt
Download as pdf or txt
You are on page 1of 11

Unit -V

Data File Handling In C++


Objectives
After going through this lesson, you would be able to:

 Understand the importance of data file for permanent storage of data


 Understand the file organization methods and file accessing methods
 Understand how standard Input/Output function work
 Distinguish between text and binary file
 Open and close a file ( text and binary)
 Read and write data in file
 Write programs that manipulate data file(s)
 Move pointer within the file

File:
A file (i.e. data file) is a named place on the disk where a sequence of related data is stored.

The objectives of computer based file organization:


(Advantage of file)

 Ease of file creation and maintenance


 Efficient means of storing and retrieving information.
 Data is stored permanently; its processing would be faster.
 Data can be retrieve/access anytime whenever required, without destroying the data.
 Same Data to be used by others
 Data required again by the same program
 Manage large volume of data in easy way (or more flexible approach)

File Organization:
File organization deals with the physical organization of the records of a file for the
convenience of storage and retrieval of data records. File organization may be either
physical file or a logical file. The three commonly used file organizations in business data
processing applications are -
 Sequential – In a sequential file, records are stored one after another in an ascending
or descending order determined by the value of the key field of the records.
Advantages:
o Simple to understand.
o Easy to maintain and organize
o Loading a record requires only the record key.
o Relatively inexpensive I/O media and devices can be used.
o Easy to reconstruct the files.
o The proportion of file records to be processed is high.
Disadvantages:
o Entire file must be processed, to get specific information.
o Very low activity rate stored.
o Transactions must be stored and placed in sequence prior to processing.
o Data redundancy is high, as same data can be stored at different places with
different keys.
o Impossible to handle random enquiries.

 Direct/Random - Files in his type are stored in direct access storage devices such as
magnetic disk, using an identifying key. The identifying key relates to its actual
storage position in the file. The computer can directly locate the key to find the
desired record without having to search through any other record first. Here the
records are stored randomly, hence the name random file. It uses online system
where the response and updation are fast.
Advantages:
o Records can be immediately accessed for updation.
o Several files can be simultaneously updated during transaction processing.
o Transaction need not be sorted.
o Existing records can be amended or modified.
o Very easy to handle random enquiries.
o Most suitable for interactive online applications.
Disadvantages:
o Data may be accidentally erased or over written unless special precautions are
taken.
o Risk of loss of accuracy and breach of security. Special backup and
reconstruction procedures must be established.
o Less efficient use of storage space.
o Expensive hardware and software are required.
o High complexity in programming.
o File updation is more difficult when compared to that of sequential method.

 Index Sequential - Here the records are stored sequentially on a direct access device
i.e. magnetic disk and the data is accessible randomly and sequentially. It covers the
positive aspects of both sequential and direct access files. The type of file
organization is suitable for both batch processing and online processing. Here, the
records are organized in sequence for efficient processing of large batch jobs but an
index is also used to speed up access to the records. Indexing permit access to
selected records without searching the entire file.
Advantages:
o Permits efficient and economic use of sequential processing technique when the
activity rate is high.
o Permits quick access to records, in a relatively efficient way when this activity
is a fraction of the work load.
Disadvantages:
o Slow retrieval, when compared to other methods.
o Does not use the storage space efficiently.
o Hardware and software used are relatively expensive.
The selection of a particular method depends on:
 Type of application.
 Method of processing.
 Size of the file.
 File inquiry capabilities.
 File volatility.
 The response time.
File Access Methods:
Access means retrieve or read data from disk file and transferred into primary memory and
then process it. There are three methods to access file data. These are:
1. Sequential Access: Read data from beginning to end in serially/sequential way
2. Random/Direct Access: Read data at desirable position directly.
3. Dynamic Access: Read both methods whenever, required.

Basic File operations/ File processing activities:


There are different operations that can be carried out on a file. These are:
 Naming a file
 Creation/Opening of a new file.
 Opening existing file
 Reading data from a file
 Writing data to a file
 Moving to a specific location in a file (seeking), and
 Closing a file
File stored on the disk:
– Stored as sequence of bytes, logically contiguous (may not be physically contiguous
on disk).
– The last byte of a file contains the end-of-file character (EOF), with ASCII code 1A
(hex).
– While reading a text file, the EOF character can be checked to know the end.

Type of file:
Two kinds of files:
1. Text file:
– A text file is usually considered as sequence of lines. Line is a sequence of
characters (ASCII), stored on permanent storage media.
– Text files are stored in human readable form and they can also be created using
any text editor.
2. Binary file:
– A binary file contains arbitrary binary data i.e. numbers stored in the file, can be
used for numerical operation(s).
– They can hold a higher amount of data, are not readable easily, and provides
better security than text files.
– Binary files are mostly the .bin files in your computer.
– In binary files, no delimiters are used for a line and no translations occur here.
– It can contain non-ASCII characters
 Image, audio, video, executable, etc.
File naming rules in C++:
 File name is a string of characters that make up a valid filename for the operating
system.
 It may contain two parts-
o A primary name and
 First letter must be alphabet
 Maximum length can be 8 chars long
 Special character not allowed
o An optional period with the extension.
 Maximum three chars long
 Example valid file name are:
 input.dat
 store
 PROG.C
 Text. out

Types of Data Communicate with Program:

In a program involves either or both of the following kinds of data communication:


a) Data transfer between the console unit and the program.
b) Data transfer between the program and disk file.

The various components involved in file processing are shown in Figure:

Figure: Consol-Program-File interaction


Stream: It refers to a sequence of bytes. It acts either as source from which the input
data can be obtained or as a destination to which the output data can be sent.

The I/O 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 (extracts (or reads) data from the file) and the one that receives data from the
program is known as output stream (inserts (or writes) data to the file).

The input operation involves the creation of an input stream and linking it with the
program and the input file. Similarly, the output operation involves establishing an
output stream with the necessary links with the program and the output file

Figure: File input and output streams


File Handling in C++ :
File handling in C++ enables us to create, update, read, and delete the files stored on the
local file system through our C program. The following operations can be performed on a file
 Creation/Opening of a new file.
 Opening existing file
 Reading data from a file
 Writing data to a file
 Moving to a specific location in a file (seeking), and
 Closing a file

Classes for file stream operations:


 There are many built in classes of C++, that define the file handling methods.
 These include ifstream, ofstream and fstream.
 These classes are derived from fstreambase and from the corresponding
iostream class as shown in figure.
 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.
e,.g. #include<fstream.h>
There are three classes for handling 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.
The hierarchy of C++ file stream classes is shown in figure:

Figure: stream classes for file operations

Table : Details of file stream classes

Class Description
ifstream Support input operations. Contains open() with default input
mode. Inherits the functions gets(), getline(), read(),
seekg(), and tellg() functions from istream

ofstream Support output operations. Contains open() with default output


mode. Inherits the functions put(), seekp(), tellp() and
write() functions from ostream

fstream Support for simultaneous input and output operations. Contains


open() with default input mode. Inherits all the functions from
ifstream and ostream classes through iostream.

fstreambase Provides operations common to the file stream. Serves as a base


for fstream, ifstream and ofstream class. Contains open() and
close() functions.

filebuf The class filebuf sets the file buffer to read and write. It contains
Openprot constant used in the open() of file stream classes.
Also contain close() and open() as members
Opening and closing a file

Open 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. An open file is represented within a
program by a stream (i.e., an object of one of these classes) and any input or output
operation performed on this stream object will be applied to the physical file associated to it.

Before storing data onto the secondary storage, firstly we must specify following things
aboutthe file and its intended use:
 Suitable name for the file
 Data type and Data Structure
 Purpose / Mode
 Opening method

In order to open a file we must first create a file stream and them link it to the filename. A
file stream can be define using the classes ifstream, ofstreram, and fstream that are
contained in the header file fstream. The class to be used depends upon the purpose, that
is whether we want to read data from the file or write data to it.

A file can be opened in two ways:

1. Using the member function open() of the class – used when we want to
manage multiple files using one stream.
2. Using the constructor of the class – used when we use only one file in the
steam.

1. Opening Files Using open():

The function open() can be used to open multiple files that use the same stream object.
This is done as follows:

file-stream-class str-obj;
str-obj.open(“filename”, mode);

Where filename is a string representing the name of the file to be opened, and mode is an
optional parameter with a combination of the following flags:

Parameter Meaning
ios::in Open for input operations.
ios::out Open for output operations.
ios::binary Open in binary mode.
ios::ate Set the initial position at the end of the file.
ios::app Append to end-of-fle
ios::trunc Delete the contents of the file it exists
ios::nocreate Open fails if the file does not exist
ios::noreplace Open fails if the file already exists
All these flags can be combined using the bitwise operator OR (|). For example, if we want
to open the file student.dat in binary mode to add data we could do it by the following call to
member function open:
Example:

ofstream st;
st.open ("student.dat", ios::out | ios::app | ios::binary);
Each of the open member functions of classes ofstream, ifstream and fstream has a
default mode that is used if the file is opened without a second argument:

class default mode parameter


ofstream ios::out
ifstream ios::in
fstream ios::in | ios::out

For ifstream and ofstream classes, ios::in and ios::out are automatically and respectively
assumed, even if a mode that does not include them is passed as second argument to
the open member function (the flags are combined).
Example:

ofstream outf; // create stream (for output)


outf.open ("emp.dat"); // connect stream to emp.dat
… …….
… ……
outf.close(); // disconnect stream from emp.dat

2. OPENING FILE USING CONSTRUCTORS:

A filename is used to initialize the file stream object. This involve the following steps:
This involves two steps:
1. Create file stream subject 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.
2. Initialize the file object with the desired filename.

The following statement opens a file “sample.txt” for output:


ofstream outf("sample.txt"); //output only
Similary, the he following statement opens a file “sample.txt” for input:
ifstream inf("sample.txt"); //output only

Closing File
The file should be closed at the end if it is opened either through constructor or open
( ) function. The General format is:
stream_object.close ( );
outf.close();
inf.close();
Program 1:
Create a New file as name “stud.dat” with information Roll No, Name,
and three subject Marks and Read the created file and calculate Total
and percentage marks and display it.

// File Create using constructor and Read & display information


//Working with single File
#include<iostream.h>
#include<fstream.h>
#include<conio.h>
void main()
{ int roll_no, m1,m2,m3,total; Variable Declare in
float per; primary memory(RAM)
char name[15];
ofstream outf("stud.dat"); // connect student.dat to outf
clrscr();
cout<<"Enter Student Information: "<<endl; get data from keyboard
cout<<"Name of student : "; cin>>name;
cout<<"Subject1 Marks : "; cin>>m1; /
cout<<"Subject2 Marks : "; cin>>m2;
cout<<"Subject3 Marks : "; cin>>m3;
outf<<name<<endl;
outf<<m1<<endl; Write into the file
outf<<m2<<endl;
outf<<m3<<endl;
outf.close(); // disconnect stud.dat

ifstream inf("stud.dat"); // connect student.dat to inf


inf>>name;
inf>>m1; reading from the file
inf>>m2;
inf>>m3; // read from file stud.dat
total = m1+m2+m3;
per = total/3.0; Process data i
cout<<"\n\n";
cout<<"Student Information: "<<endl;
cout<<"Name of student : "<<name<<endl;
cout<<"Subject1 Marks : "<<m1<<endl; Display on the Sceen
cout<<"Subject2 Marks : "<<m2<<endl;
cout<<"Subject3 Marks : "<<m3<<endl;
cout<<"Total Marks : "<<total<<endl;
cout<<"percentage Marks: "<<per<<endl;
inf.close(); // disconnect stud.dat
getch(); }
The Output of Program:

Program 1:
Write a Program create a file as name „emp‟ contains emp_name,
Basic_pay, DA (154% of BP) and HRA (20% of BP). Read the created file
and entire information on the screen.

// File Create using open() function and Read & display information
#include<iostream.h>
#include<fstream.h>
#include<conio.h>
void main()
{
char emp_nm[15];
int bp;
float da,hra,gross;

ofstream outf; // create output stream


ifstream inf; // create input stream
clrscr();
outf.open("emp");
cout<<"Enter Employee information: "<<endl;
cout<<"Name of employee : "; cin>>emp_nm; //get information
cout<<"Basic Pay : "; cin>>bp; // from key board
da = bp * 1.54;
hra = bp*.20;
gross = bp+da+hra;
outf<<emp_nm<<endl; // write to file
outf<<bp<<endl;
outf<<da<<endl;
outf<<hra<<endl;
outf.close(); // disconnect emp

inf.open("emp"); // connect emp to inf


inf>>emp_nm; // read from file emp
inf>>bp;
inf>>da;
inf>>hra;
inf>>gross;
cout<<"\n\n";
cout<<"Emp Name : "<<emp_nm<<endl;
cout<<"basic pay : "<<bp<<endl;
cout<<"DA : "<<da<<endl;
cout<<"HRA : "<<hra<<endl;
cout<<"Gross : "<<gross<<endl;
inf.close(); // disconnect stud.dat
getch();
}

The Output of Program:

You might also like