0% found this document useful (0 votes)
78 views18 pages

Lab 12

The document provides instructions for a lab on file processing in C++. It discusses sequential and random access files, and includes tasks on reading from and writing to files, as well as manipulating file pointers. Code examples are given throughout.

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)
78 views18 pages

Lab 12

The document provides instructions for a lab on file processing in C++. It discusses sequential and random access files, and includes tasks on reading from and writing to files, as well as manipulating file pointers. Code examples are given throughout.

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/ 18

CC-211L

Object Oriented Programming

Laboratory 12

File Processing

Version: 1.0.0

Release Date: 13-04-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 Sequential File
o Random-Access File
 Activities
o Pre-Lab Activity
 Files and Streams
 Creating a Sequential File
– Opening a file
– Closing a file
 Task 01
 Task 02
o In-Lab Activity
 File Position Pointers
– Member functions tellp() and tellg()
 Updating a Sequential File
 Creating a Random File
 Writing Data to a Random File
 Reading Data from a Random File
 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 12 – File Processing Page 2 of 18


CC-211L Object Oriented Programming FALL 2022

Learning Objectives:
 Files and Streams
 Create a Sequential File
 Read a Sequential File
 Update a Sequential File
 Random Access File
 Create a Random-Access File
 Read a Random-Access File

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 12 – File Processing Page 3 of 18


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.

Sequential File:
A sequential file is simply a file where the data is stored one item after another. A more technical
definition would be that a sequential file is a collection of data stored on a disk in a sequential, non-
indexed, manner. C++ treats all such files simply as a sequence of bytes. Each file ends with a special
end of file marker.
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.

Laboratory 12 – File Processing Page 4 of 18


CC-211L Object Oriented Programming FALL 2022

Activities:
Pre-Lab Activities:
Files and Streams:
C++ views each file simply as a sequence of bytes. Each file ends either with an end-of-file marker or
at a specific byte number recorded in an operating-system-maintained administrative data structure.
When a file is opened, an object is created, and a stream is associated with the object.
To perform file processing in C++, headers <iostream> and <fstream> must be included.
Header <fstream> includes the definitions for the stream class templates

 basic_ifstream—a subclass of basic_istream for file input


 basic_ofstream—a subclass of basic_ostream for file output
 basic_fstream—a subclass of basic_iostream for file input and output.
In addition, the <fstream> library provides typedef aliases for these template specializations:

 ifstream is an alias for basic_ifstream<char>


 ofstream is an alias for basic_ofstream<char>
 fstream is an alias for basic_fstream<char> .

Creating a Sequential File:


Example:

Fig. 01 (Sequential File)


Opening a file:
Following syntax is followed to open a file:

Ofstream outClientFile;
outClientFile.open(Filename, Mode)
Following are the different modes to open a file:

Laboratory 12 – File Processing Page 5 of 18


CC-211L Object Oriented Programming FALL 2022

Mode Description
ios::app Append all output to the end of the file.
ios::ate Open a file for output and move to the end of the file. Data can be written
anywhere in the file.
ios::in Open file for input.
ios::out Open file for output.
ios::trunc Discard’s the file content.
ios::binary Open a file for binary.

Closing a file:
File is closed implicitly when a destructor for the corresponding object is called. It can also be called
explicitly by using member function close:
outClientFile.close();
Reading a Sequential file:
Example:

Fig. 02 (Reading Sequential File )

File Content:

Fig. 03 (Reading Sequential File)

Laboratory 12 – File Processing Page 6 of 18


CC-211L Object Oriented Programming FALL 2022

Output:

Fig. 04 (Reading Sequential File)

Laboratory 12 – File Processing Page 7 of 18


CC-211L Object Oriented Programming FALL 2022

Task 01: Word Occurrence [Estimated time 20 minutes / 15 marks]

 Create a text file and write some text in it


 Read the file contents using Sequential Access
 Count the words occurrence and display the most repetitive word/s on the Console

Task 02: Map 2D Array [Estimated time 20 minutes / 15 marks]


 Create a text file and write 2D array contents as shown in the figure

Fig. 05 (Pre-Lab Task)

 Read the file contents using Sequential Access


 Map the contents to a 2D array and display it on the Console

Laboratory 12 – File Processing Page 8 of 18


CC-211L Object Oriented Programming FALL 2022

In-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. 06 (File Position Pointer)

File Content:

Laboratory 12 – File Processing Page 9 of 18


CC-211L Object Oriented Programming FALL 2022

Fig. 07 (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. 08 (File Position Pointer)

Output:

Fig. 09 (File Position Pointer)


Updating a Seque ntial File:
Data that is formatted and written to a sequential file cannot be modified easily without the risk of
destroying other data in the file. If we want to modify a record of data, the new data may be longer
than the old one and it could overwrite parts of the record following it.

Example:
Following example demonstrates the overwriting of data while trying to update a sequential file.

Laboratory 12 – File Processing Page 10 of 18


CC-211L Object Oriented Programming FALL 2022

Fig. 10 (Updating Sequential File)

Output:

Fig. 11 (Updating Sequential File)

File Content (Before Updating):

Fig. 12 (Updating Sequential File)

File Content (After Updating):

Fig. 13 (Updating Sequential File)


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:

Laboratory 12 – File Processing Page 11 of 18


CC-211L Object Oriented Programming FALL 2022

Fig. 14 (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 12 – File Processing Page 12 of 18


CC-211L Object Oriented Programming FALL 2022

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

Output:

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


Reading Data from a Random File:
Example:

Laboratory 12 – File Processing Page 13 of 18


CC-211L Object Oriented Programming FALL 2022

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

Output:

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

Laboratory 12 – File Processing Page 14 of 18


CC-211L Object Oriented Programming FALL 2022

Task 01: Compare Files [Estimated time 20 minutes / 20 marks]

 Write a program that creates two files


o file1.dat
o file2.dat
 Input same data to both files and show data of both files.
 Now compare data of both files and display a message “both files have same content”.
 Now modify data in file2 just by appending some more content at the end of file, again show data
and compare them and display message “files have different content”.

Task 02: Students Rubric [Estimated time 30 minutes / 20 marks]

 Make a class rubric with data members:


o regno(RegNo. of student),
o clearity(value should be nonnegative and less than or equal to 2),
o completeness(value should be nonnegative and less than or equal to 3),
o accuracy(value should be non-negative and less than or equal to 3),
o time(value should be nonnegative and less than or equal to 2), and
o total_marks.
 Class has member function:
o input() that inputs data for regno, clearity, completeness, accuracy, time, and
total_marks=clearity+completeness+accuracy+time.
o output() that output data to student.txt and
o show() that show content of student.txt by reading them from the file.
 Create an object and enter data for any three CC211 student store their data in student.txt and
display them

Task 03: Student Record [Estimated time 30 minutes / 30 marks]

 Create a class named Student to store information about a student, including their name, ID, GPA,
and list of courses.
 Implement the following methods in the class:
o void setStudentData(): This method should prompt the user to enter the student's name, ID,
GPA, and list of courses, and store the data in the object's member variables.
o void printStudentData(): This method should print the student's name, ID, GPA, and list of
courses to the console.
o void writeToFile(std::ofstream& file): This method should write the student's data to the
specified file in a custom format. Each line in the file should contain the student's name, ID,
GPA, and comma-separated list of courses.
o void readFromFile(std::ifstream& file): This method should read the student's data from
the specified file in the custom format and store it in the object's member variables.
 In your main() function, create an array of Student objects, prompt the user to enter data for each
student, and write the data to a file named "studentRecord.txt". Then, read the data from the file
and print it to the console.

Laboratory 12 – File Processing Page 15 of 18


CC-211L Object Oriented Programming FALL 2022

Post-Lab Activities:
Task 01: Library Management [Estimated time 60 minutes / 40 marks]
Create a program that simulates a library management system. Your program should have the
following classes:

 Book class: This class should contain information about a book, including its title, author,
publisher, publication year, ISBN, and status (e.g., available, checked out). Implement the
following methods in the class:
o void setBookData(): This method should prompt the user to enter the book's data, and store
the data in the object's member variables.
o void printBookData(): This method should print the book's data to the console.
o void writeToFile(std::ofstream& file): This method should write the book's data to the
specified file.
o void readFromFile(std::ifstream& file): This method should read the book's data from the
specified file and store it in the object's member variables.
 Library class: This class should contain information about a library, including its name, address,
and list of books. Implement the following methods in the class:
o void addBook(Book b): This method should add the specified book to the library's list of
books.
o void removeBook(Book b): This method should remove the specified book from the library's
list of books.
o void printLibraryData(): This method should print the library's name, address, and list of
books to the console.
o void writeToFile(std::ofstream& file): This method should write the library's data to the
specified file in a custom format. The first line of the file should contain the library's name
and address, followed by a blank line. Each subsequent line should contain the data for one
book.
o void readFromFile(std::ifstream& file): This method should read the library's data from the
specified file in the custom format and store it in the object's member variables.
 In your main() function, create a Library object, prompt the user to enter data for the library and
its books, and write the data to a file named "library.txt". Then, read the data from the file and
print it to the console.
 Your program should also allow the user to check out and return books from the library.
Implement the following methods for the Library class:
o void checkOutBook(Book b): This method should mark the specified book as checked out.
o void returnBook(Book b): This method should mark the specified book as available again.

Laboratory 12 – File Processing Page 16 of 18


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: [30 marks]
 Task 01: Word Occurrence [15 marks]
 Task 02: Map 2D Array [15 marks]
 Division of In-Lab marks: [70 marks]
 Task 01: Compare Files [20 marks]
 Task 02: Students Rubric [20 marks]
 Task 03: Student Record [30 marks]
 Division of Post-Lab marks: [40 marks]
 Task 01: Library Management [40 marks]

References and Additional Material:


 C++ Files and Streams
https://www.tutorialspoint.com/cplusplus/cpp_files_streams.htm

Laboratory 12 – File Processing Page 17 of 18


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 12 – File Processing Page 18 of 18

You might also like