0% found this document useful (0 votes)
71 views20 pages

Lab 14

The document provides instructions for a lab on random-access files and exception handling. It includes background on files, streams, random-access files, exceptions, and exception handling. It outlines pre-lab, in-lab, and post-lab activities focused on random file access, exceptions, and completing programming tasks.

Uploaded by

nomanbsit
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
71 views20 pages

Lab 14

The document provides instructions for a lab on random-access files and exception handling. It includes background on files, streams, random-access files, exceptions, and exception handling. It outlines pre-lab, in-lab, and post-lab activities focused on random file access, exceptions, and completing programming tasks.

Uploaded by

nomanbsit
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 20

CC-211L

Object Oriented Programming

Laboratory 14

Random-Access Files & Exception Handling

Version: 1.0.0

Release Date: 04-05-2023

Department of Information Technology


University of the Punjab
Lahore, Pakistan
CC-211L Object Oriented Programming FALL 2022

Contents:
• Learning Objectives
• Required Resources
• General Instructions
• Background and Overview
o Files and Streams
o Random-Access Files
o Exception
o Exception Handling
• Activities
o Pre-Lab Activity
▪ File Position Pointers
▪ Task 01
o In-Lab Activity
▪ Creating a Random-Access File
▪ Writing data to a Random File
▪ Reading data from a Random File
▪ Exception Handling
– C++ try
– C++ catch
– C++ throw
▪ Standard Exceptions
▪ User Defined Exceptions
▪ Rethrowing an Exception
▪ Constructor Destructor and Exception Handling
▪ Task 01
▪ Task 02
▪ Task 03
o Post-Lab Activity
▪ Task 01
• Submissions
• Evaluations Metric
• References and Additional Material
• Lab Time and Activity Simulation Log

Laboratory 14 – Random-Access Files & Exception Handling Page 2 of 20


CC-211L Object Oriented Programming FALL 2022

Learning Objectives:
• Random-Access File
• Create Random-Access File
• Write to a Random-Access File
• Read from a Random-Access File
• Defining an Exception Class
• Rethrowing an Exception
• Constructor, Destructor and Exception handling

Resources Required:
• Desktop Computer or Laptop
• Microsoft ® Visual Studio 2022

General Instructions:
• In this Lab, you are NOT allowed to discuss your solution with your colleagues, even not
allowed to ask how is s/he doing, this may result in negative marking. You can ONLY discuss
with your Teaching Assistants (TAs) or Lab Instructor.
• Your TAs will be available in the Lab for your help. Alternatively, you can send your queries
via email to one of the followings.

Teachers:
Course Instructor Prof. Dr. Syed Waqar ul Qounain [email protected]
Lab Instructor Azka Saddiqa [email protected]

Saad Rahman [email protected]


Teacher Assistants
Zain Ali Shan [email protected]

Laboratory 14 – Random-Access Files & Exception Handling Page 3 of 20


CC-211L Object Oriented Programming FALL 2022

Background and Overview:


Files and Streams:
Files are used to store data in a storage device permanently. File handling provides a mechanism to
store the output of a program in a file and to perform various operations on it.
A stream is an abstraction that represents a device on which operations of input and output are
performed. A stream can be represented as a source or destination of characters of indefinite length
depending on its usage.
Random-Access File:
Random file access enables us to read or write any data in our disk file without having to read or write
every piece of data before it while in Sequential files to reach data in the middle of the file you must go
through all the data that precedes it. We can quickly search for data, modify data, delete data in a
random-access file.
Exception:
An exception is a problem that arises during the execution of a program. It is a response to an
exceptional circumstance that arises while a program is running, such as an attempt to divide by zero.
Exception Handling:
Exception handling is the process of handling errors and exceptions in such a way that they do not
hinder normal execution of the system. For example, User divides a number by zero, this will compile
successfully but an exception or run time error will occur due to which our applications will be crashed.

Laboratory 14 – Random-Access Files & Exception Handling Page 4 of 20


CC-211L Object Oriented Programming FALL 2022

Activities:
Pre-Lab Activities:
File Position Pointers:
<istream> and <ostream> classes provide member functions for repositioning the file pointer (the byte
number of the next byte in the file to be read or to be written). These member functions are:

• seekg (seek get) for istream class


• seekp (seek put) for ostream class

Following are some examples to move a file pointer:


• inClientFile.seekg(0) - repositions the file get pointer to the beginning of the file
• inClientFile.seekg(n, ios:beg) - repositions the file get pointer to the n-th byte of the file
• inClientFile.seekg(m, ios:end) - repositions the file get pointer to the m-th byte from the end of
file
• inClientFile.seekg(0, ios:end) - repositions the file get pointer to the end of the file

The same operations can be performed with <ostream> function member seekp.

Member functions tellg() and tellp():


Member functions tellg and tellp are provided to return the current locations of the get and put
pointers, respectively.

long location = inClientFile.tellg();

To move the pointer relative to the current location use ios:cur


inClientFile.seekg(n, ios:cur) - moves the file get pointer n bytes forward.

Example:
In this example, we open a file named “example.txt” for writing using std::ofstream. We then write
some data to the file using the << operator. We use the tellp() function to get the current position of the
file pointer and use seekp() to move the file pointer back to the beginning of the file. We then write
some more data to the file and use seekp() again to move the file pointer to the end of the file. Finally,
we write some more data to the file and close it.

Fig. 01 (File Position Pointer)

Laboratory 14 – Random-Access Files & Exception Handling Page 5 of 20


CC-211L Object Oriented Programming FALL 2022

File Content:

Fig. 02 (File Position Pointer)


Example:
In this example, we open a file named "example.txt" and use the tellg() function to get the current
position of the file pointer. We then use the seekg() function to move the file pointer to the end of the
file and use tellg() again to get the size of the file. We then move the file pointer back to the beginning
of the file using seekg() and read the data from the file using the read() function. Finally, we output the
data to the console and close the file.

Fig. 03 (File Position Pointer)


Output:

Fig. 04 (File Position Pointer)

Laboratory 14 – Random-Access Files & Exception Handling Page 6 of 20


CC-211L Object Oriented Programming FALL 2022

Task 01: Read Records [Estimated time 30 minutes / 20 marks]


Write a program that:

• Reads in a text file called “data.txt” containing records(objects) of the class “Record” with data
members:
o Id (int)
o Name (string)
o Balance (double)
• The program should then allow the user to search for a record by ID and update the balance for
that record
• Use seekg() and seekp() functions to move the read and write positions to the correct locations in
the file

Laboratory 14 – Random-Access Files & Exception Handling Page 7 of 20


CC-211L Object Oriented Programming FALL 2022

In-Lab Activities:
Creating a Random-Access File:
Instant access is possible with random access files. Individual records of a random-access file can be
accessed directly without searching many other records.

Example:

Fig. 05 (Creating a Random-Access File)


The <ostream> member function write outputs a fixed number of bytes beginning at a specific location
in memory to the specific stream. When the stream is associated with a file, the data is written beginning
at the location in the file specified by the “put” file pointer. The write function expects a first argument
of type “const char *”, hence we used the reinterpret_cast to convert the address of the blankClient to
a const char *. The second argument of write is an integer of type “size_t” specifying the number of
bytes to written. Thus, the sizeof (clientData).
Writing Data to a Random File:
Example:

Laboratory 14 – Random-Access Files & Exception Handling Page 8 of 20


CC-211L Object Oriented Programming FALL 2022

Fig. 06 (Writing Data to a Random-Access File)


Output:

Fig. 07 (Writing Data to a Random-Access File)


Reading Data from a Random File:
Example:

Laboratory 14 – Random-Access Files & Exception Handling Page 9 of 20


CC-211L Object Oriented Programming FALL 2022

Fig. 08 (Reading Data from a Random-Access File)


Output:

Fig. 09 (Reading Data from a Random-Access File)


Exception Handling:
Exception handling provides you with a way of handling unexpected circumstances like runtime errors.
So, whenever an unexpected circumstance occurs, the program control is transferred to special functions
known as handlers.
To catch the exceptions, you place some section of code under exception inspection. The exception
handing is mainly performed using three keywords namely - try, catch, and throw using following
syntax:
try
{
// code
throw exception;
}
catch(exception e)
{
// code for handling exception
}
C++ try:
The try block is used to keep the code that is expected to throw some exception. Whenever our code
leads to any exception or error, the exception or error gets caught in the catch block. In simple terms,

Laboratory 14 – Random-Access Files & Exception Handling Page 10 of 20


CC-211L Object Oriented Programming FALL 2022

we can say that the try block is used to define the block of code that needs to be tested for errors while
it is being executed.

E.g., Suppose we are dealing with databases, we should put the code that is handling the database
connection inside a try block as the database connection may raise some exceptions or errors.

C++ catch:
The catch block is used to catch and handle the error(s) thrown from the try block. If there are multiple
exceptions thrown from the try block, then we can use multiple catch blocks after the try blocks for
each exception. In this way, we can perform different actions for the various occurring exceptions. In
simple terms, we can say that the catch block is used to define a block of code to be executed if an error
occurs in the try block.

E.g., Let us take the same above example that we are dealing with the database. Now, if during the
connection, there is an exception raised inside the try block, then there should be a catch block present
to catch or accept the exception and handle the exception. The catch block ensures that the normal flow
of the code is not halted.

C++ throw:
The throw block is used to throw exceptions to the exception handler which further communicates the
error. The type of exception thrown should be same in the catch block. The throw keyword accepts one
parameter which is passed to the exception handler. We can throw both pre-defined as well as custom
exception(s) as per the requirements.

Whenever we want to explicitly throw an exception, we use the throw keyword. The throw keyword is
also used to generate the custom exception.

Following example demonstrates the overall working and syntax of try, catch, and throw in exception
handling.

Example:

Fig. 10 (Exception Handling)


Output:

Laboratory 14 – Random-Access Files & Exception Handling Page 11 of 20


CC-211L Object Oriented Programming FALL 2022

Fig. 11 (Exception Handling)


If you do not know the type of throw used in the try block, we can always use the "three dots" syntax
(...) inside the catch block, which will handle any type of exception.

Example:

Fig. 12 (Exception Handling)


Output:

Fig. 13 (Exception Handling)


Standard Exceptions:
C++ comes with a list of standard exceptions defined in <exception> class given in the table below:

Exception Description
exception This is an exception and the parent class of all standard C++ exceptions.
bad_alloc This exception is thrown by a new keyword.
bad_cast This is an exception thrown by dynamic_cast.
bad_exception A useful device for handling unexpected exceptions in C++ programs.
bad_typeid An exception thrown by typeid.
logic_error This exception is theoretically detectable by reading code.
domain_error This is an exception thrown after using a mathematically invalid domain.
invalid_argument An exception thrown for using invalid arguments.
length_error An exception thrown after creating a big std::string.
out_of_range Thrown by at method.
runtime_error This is an exception that cannot be detected via reading the code.
overflow_error This exception is thrown after the occurrence of a mathematical overflow.
range_error This exception is thrown when you attempt to store an out-of-range value.
underflow_error An exception thrown after the occurrence of mathematical underflow.

Laboratory 14 – Random-Access Files & Exception Handling Page 12 of 20


CC-211L Object Oriented Programming FALL 2022

User Defined Exceptions:


There may be situations where you want to generate some user/program specific exceptions which are
not pre-defined. In such cases C++ provided us with the mechanism to create our own exceptions by
inheriting the exception class and overriding its functionality according to our needs.

Example:

Fig. 14 (User Defined Exception)


Output:

Fig. 15 (User Defined Exception)


Rethrowing an Exception:
In the program execution, when an exception received by catch block is passed to another exception
handler then such situation is referred to as rethrowing of exception.
This is done with the help of following statement,

throw;

Laboratory 14 – Random-Access Files & Exception Handling Page 13 of 20


CC-211L Object Oriented Programming FALL 2022

The above statement does not contain any arguments. This statement throws the exception to next try
catch block.

Example:

Fig. 16 (Rethrowing Exception)


Output:

Fig. 17 (Rethrowing Exception)


Constructor Destructor and Exception Handling:
Consider the following example:
Example:

Laboratory 14 – Random-Access Files & Exception Handling Page 14 of 20


CC-211L Object Oriented Programming FALL 2022

Fig. 18 (Constructor Destructor and Exception Handling)


Output:

Fig. 19 (Constructor Destructor and Exception Handling)


Explanation:
When an exception is thrown, the objects' destructors (whose scope ends with the try block) are
automatically triggered before the catch block is performed. As a result, the preceding software outputs
"Destructing an item of Test" before “Caught 10”.

This happens when an exception is thrown from a Constructor:

Example:

Laboratory 14 – Random-Access Files & Exception Handling Page 15 of 20


CC-211L Object Oriented Programming FALL 2022

Fig. 20 (Constructor Destructor and Exception Handling)


Output:

Fig. 21 (Constructor Destructor and Exception Handling)


Explanation:
Destructors are only invoked for properly developed constructed objects. When a function object throws
an exception, the object's destructor is not invoked.

Laboratory 14 – Random-Access Files & Exception Handling Page 16 of 20


CC-211L Object Oriented Programming FALL 2022

Task 01: Employee Database [Estimated time 40 minutes / 30 marks]

• Write a program that implements a database of employee records using a random-access file
called “employees.dat”.
• Each record in the file should contain the following fields:
class Employee {
int id;
char name[50];
char department[50];
float salary;
int numSubordinates;
int* subordinateIds; // dynamically allocated array of length numSubordinates
};
• The subordinateIds array stores the IDs of each employee's subordinates, with the length of the
array specified by the numSubordinates field.
• The program should allow the user to perform the following operations:
o Add a new employee record to the file at the end.
o Delete an employee record from the file based on their ID.
o Update the fields of an employee record in the file based on their ID.
o Print the information of an employee record in the file based on their ID.
o Print the information of all employee records in the file, sorted by salary in ascending order.
Task 02: Shopping Cart [Estimated time 40 minutes / 30 marks]

• Write a program that simulates a simple shopping cart system. The program consists of an Item
class with data members:
o Name
o Price
o Total quantity
• The program should allow the user to:
o Add items to their cart
o Remove items from their cart
o View the contents of their cart
o Calculate the total cost of the items in their cart
• The program should handle any errors that may occur during input or calculation, such as:
o Invalid input
o Out-of-stock items
o Insufficient funds.
Task 03: Sort Names [Estimated time 30 minutes / 20 marks]

• Create a program that reads in a list of names from a file and sorts them alphabetically.
• If any of the names in the file contain a non-alphabetic character, the program should throw a
custom exception called “InvalidNameException”.
• To accomplish this task, you'll need to create a “FileReader” class that reads the contents of the
file. Inside the FileReader class, you should define a member function called “readNames” that
takes the file name as a parameter and reads the names from the file one by one. If any of the
names contain a non-alphabetic character, the FileReader class should throw the
InvalidNameException.
• Next, you'll need to create a “NameSorter” class that takes the list of names as a parameter and
sorts them alphabetically. If any of the name length is greater than 15, the NameSorter class
should throw the custom InvalidLength exception.

Laboratory 14 – Random-Access Files & Exception Handling Page 17 of 20


CC-211L Object Oriented Programming FALL 2022

Post-Lab Activities:
Task 01: Inventory Management [Estimated time 60 minutes / 50 marks]

• Create a program that simulates a simple inventory management system. The program should be
able to read in a list of items and their corresponding quantity from a file, allow the user to add or
remove items from the inventory, and output the updated inventory to a new file.
• The detailed description of the requirements are:
o The program should read in the inventory information from a file. Each line of the file should
contain the following information:
▪ Item name (string)
▪ Item quantity (integer)
o The program should then display the inventory information to the user, along with options to
add or remove items from the inventory.
o If the user chooses to add an item to the inventory, they should be prompted to enter the item
name and quantity. The program should then update the inventory accordingly.
o If the user chooses to remove an item from the inventory, they should be prompted to enter
the item name. The program should then update the inventory accordingly, but only if there
are enough items in the inventory to remove.
o If the user enters an invalid item name, the program should throw a custom exception that
informs the user of the error and prompts them to try again.
o After each modification to the inventory, the program should write the updated inventory
information to a new file using random-access file handling.
o The program should continue to display the updated inventory and prompt the user for actions
until the user chooses to exit the program.

Laboratory 14 – Random-Access Files & Exception Handling Page 18 of 20


CC-211L Object Oriented Programming FALL 2022

Submissions:
• For In-Lab Activity:
▪ Save the files on your PC.
▪ TA’s will evaluate the tasks offline.
• For Pre-Lab & Post-Lab Activity:
▪ Submit the .cpp file on Google Classroom and name it to your roll no.

Evaluations Metric:
• All the lab tasks will be evaluated offline by TA’s
• Division of Pre-Lab marks: [20 marks]
▪ Task 01: Read Records [20 marks]
• Division of In-Lab marks: [80 marks]
▪ Task 01: Employee Database [30 marks]
▪ Task 02: Shopping Cart [30 marks]
▪ Task 03: Sort Names [20 marks]
• Division of Post-Lab marks: [50 marks]
▪ Task 01: Inventory Management [50 marks]

References and Additional Material:


• C++ Files and Streams
https://www.tutorialspoint.com/cplusplus/cpp_files_streams.htm
• Exception Handling
https://www.tutorialspoint.com/cplusplus/cpp_exceptions_handling.htm
• Rethrowing Exceptions
https://www.learncpp.com/cpp-tutorial/rethrowing-exceptions/
• Exception Handling and Object Destruction
https://www.geeksforgeeks.org/exception-handling-and-object-destruction-in-cpp/

Laboratory 14 – Random-Access Files & Exception Handling Page 19 of 20


CC-211L Object Oriented Programming FALL 2022

Lab Time Activity Simulation Log:


• Slot – 01 – 00:00 – 00:15: Class Settlement
• Slot – 02 – 00:15 – 00:40: In-Lab Task
• Slot – 03 – 00:40 – 01:20: In-Lab Task
• Slot – 04 – 01:20 – 02:20: In-Lab Task
• Slot – 05 – 02:20 – 02:45: Evaluation of Lab Tasks
• Slot – 06 – 02:45 – 03:00: Discussion on Post-Lab Task

Laboratory 14 – Random-Access Files & Exception Handling Page 20 of 20

You might also like