Extended Case Study for removing an existing record from file:
Program plan:
- Include the required header files in your program.
- Define a class “Personal” with the following functions.
- Define the default constructor “Personal()” that initializes the member variables.
- Define the constructor “Personal()” with arguments that initializes the member variables.
- Define the function “writeToFile()” to write a record to the output stream.
- Define the function “writeNullToFile()” to write a null record to the output stream.
- Define the function “readFromFile()” to read a record from the input stream.
- Define the function “readKey()” to read SSN from console.
- Define the function “size()” to get the size of a record.
- Define the function “operator==()” to check the equality of the two records.
- Define the function “isNull()” to check the current record is deleted record.
- Define the function “writeLegibly()” to write a record to the output stream.
- Define the function “operator<<()” to write a record to the output stream.
- Define the function “readFromConsole()” to read a record from the input stream.
- Define the function “operator>>()” to read a record from the output stream.
- Define a class “Student” with the following functions.
- Define the default constructor “Student()” that initializes the member variables.
- Define the constructor “Student()” with arguments that initializes the member variables.
- Define the function “writeToFile()” to write a record to the output stream.
- Define the function “writeNullToFile()” to write a null record to the output stream.
- Define the function “readFromFile()” to read a record from the input stream.
- Define the function “size()” to get the size of a record.
- Define the function “writeLegibly()” to write a record to the output stream.
- Define the function “operator<<()” to write a record to the output stream.
- Define the function “readFromConsole()” to read a record from the input stream.
- Define the function “operator>>()” to read a record from the output stream.
- Define the function “isNull()” to check the current record is deleted record.
- Define a class “
Database ” with the following functions.- Define the default constructor “Database()” that initializes the member variables.
- Define the function “run()” that processes the user wishes.
- Define the function “add()” to add a record to the database.
- Define the function “find()” to find a record in the database.
- Define the function “modify()” to modify the existing record.
- Define the function “remove()” to delete an existing record.
- Define the function “operator<<()” to write the database to the output stream.
- Define the function “print()” to display the database.
- Define the function “main()”.
- Create a database for “Personal” and call the function “run()”.
/**********************************************************
* This program Extends the case study for removing an *
* existing record. *
**********************************************************/
Explanation of Solution
Program:
//personal.h.
#ifndef PERSONAL
#define PERSONAL
// Include the required header files
#include<iostream>
#include <fstream>
#include <cstring>
using namespace std;
//Personal class declaration.
class Personal
{
//Access Specifier.
public:
//constructor.
Personal();
//Argumented constructor.
Personal(char*,char*,char*,int,long);
//Function to write Person data to file.
void writeToFile(fstream&) const;
//Function to write null record to file.
void writeNullToFile(fstream&) ;
//Function to read Person data from file.
void readFromFile(fstream&);
//Function read SSN
void readKey();
//Function to determine record is null
bool isNull();
//Function that returns the size of a record.
int size() const
{
//Sum all the fields length and return it.
return 9 + nameLen + cityLen + sizeof(year) + sizeof(salary);
}
/*Function to check the passed the record is equal to the current record.*/
bool operator==(const Personal& pr) const
{
//Compare the SSN's of current record and pr.
/*If they equal the function return true. otherwise it return false.*/
return strncmp(pr.SSN,SSN,9) == 0;
}
//Access specifier.
protected:
//Declare variables.
const int nameLen, cityLen;
char SSN[10], *name, *city;
int year;
long salary;
//Function to write the record to the output stream.
ostream& writeLegibly(ostream&);
/*Overload the operator << to write to the output stream.*/
friend ostream& operator<<(ostream& out, Personal& pr)
{
//Call the member function to write.
return pr.writeLegibly(out);
}
//Function to read a record from the input stream.
istream& readFromConsole(istream&);
/*Overload the operator >> to read fromo the input stream.*/
friend istream& operator>>(istream& in, Personal& pr)
{
//Call the member function to read.
return pr.readFromConsole(in);
}
};
#endif
//personal.cpp
//Include the header files.
#include "personal.h"
//Constructor that fixes the length for name and city.
Personal::Personal() : nameLen(10), cityLen(10)
{
/*Create the character array for name and city with specified size.*/
name = new char[nameLen+1];
city = new char[cityLen+1];
}
//Constructor with input arguments.
Personal::Personal(char *ssn, char *n, char *c, int y, long s) :
nameLen(10), cityLen(10)
{
/*Create the character array for name and city with specified size.*/
name = new char[nameLen+1];
city = new char[cityLen+1];
//Copy the passed SSN
strcpy(SSN,ssn);
//Copy the name.
strcpy(name,n);
//Copy the city.
strcpy(city,c);
//store the year.
year = y;
//Store the salary.
salary = s;
}
//Function to write the record into the output stream.
void Personal::writeToFile(fstream& out) const
{
//Write the SSN.
out.write(SSN,9);
//Write the name.
out.write(name,nameLen);
//Write the city.
out.write(city,cityLen);
/*Convert the year into char* and write it on the output.*/
out.write(reinterpret_cast<const char*>(&year),sizeof(int));
/*Convert the salary into char* and write it on the output.*/
out.write(reinterpret_cast<const char*>(&salary),sizeof(int));
}
//Function to write the null record into the output stream.
void Personal::writeNullToFile(fstream& out)
{
/* First Character of the SSN should be marked with '#'*/
SSN[0]='#';
//Write the SSN.
out.write(SSN,9);
//Write the name.
out.write(name,nameLen);
//Write the city.
out.write(city,cityLen);
/*Convert the year into char* and write it on the output.*/
out.write(reinterpret_cast<const char*>(&year),sizeof(int));
/*Convert the salary into char* and write it on the output.*/
out.write(reinterpret_cast<const char*>(&salary),sizeof(int));
}
//Function to read a record from the input stream.
void Personal::readFromFile(fstream& in)
{
//Read the SSN
in.read(SSN,9);
//Read the name.
in.read(name,nameLen);
//Read the city.
in.read(city,cityLen);
//Convert the char* to int and store it in year.
in.read(reinterpret_cast<char*>(&year),sizeof(int));
//Convert the char* to int and store it in salary.
in.read(reinterpret_cast<char*>(&salary),sizeof(int));
}
//Function to read the SSN from the user.
void Personal::readKey()
{
//Declare the variables.
char s[80];
//Prompt the user.
cout << "Enter SSN: ";
//Read the SSN
cin.getline(s,80);
//copy the SSN.
strncpy(SSN,s,9);
}
//Function to check record is null.
bool Personal::isNull()
{
/*Return true if SSN[0] is '#', otherwise return false */
return SSN[0]=='#';
}
//Function to write the record to the console.
ostream& Personal::writeLegibly(ostream& out)
{
//Terminate the strings.
SSN[9] = name[nameLen] = city[cityLen] = '\0';
//Write SSN, name, year, city, salary to the console.
out << "SSN = " << SSN << ", name = " << name<< ", city = " << city << ", year = " << year<< ", salary = " << salary;
//Return the output stream.
return out;
}
//Function to read a record from the console.
istream& Personal::readFromConsole(istream& in)
{
//Terminate the strings.
SSN[9] = name[nameLen] = city[cityLen] = '\0';
char s[80];
//Read SSN in variable 's'.
cout << "SSN: ";
in.getline(s,80);
//Copy the SSN from 's'.
strncpy(SSN,s,9);
//Read name in variable 's'.
cout << "Name: ";
in.getline(s,80);
//Copy the name from 's'.
strncpy(name,s,nameLen);
//Read the city in 's'.
cout << "City: ";
in.getline(s,80);
//Copy the city from 's'.
strncpy(city,s,cityLen);
//Read the year.
cout << "Birthyear: ";
in >> year;
//Read the salary.
cout << "Salary: ";
in >> salary;
in.ignore();
//Return the input stream.
return in;
}
//student.h
//Defining the header file.
#ifndef STUDENT
#define STUDENT
//Include the header file
#include "personal.h"
//Derive the class Student from Personal
class Student : public Personal
{
//Access specifier.
public:
//Constructor
Student();
//Constructor with arguments*/
Student(char*,char*,char*,int,long,char*);
//Function to write record to the output stream.
void writeToFile(fstream&) const;
//Function to write null record to file.
void writeNullToFile(fstream&) ;
//Function to read a Student record from input stream.
void readFromFile(fstream&);
//Function to get the size of the Student record.
int size() const
{
/*Call the base call method to find the record size.*/
return Personal::size() + majorLen;
}
//Function to determine record is null
bool isNull();
//Access specifier.
protected:
//Declare variables.
char *major;
const int majorLen;
//Function to write the record to the output stream.
ostream& writeLegibly(ostream&);
/*Overaloaded operator << to write to the output stream.*/
friend ostream& operator<<(ostream& out, Student& sr)
{
//Call member function to write the record.
return sr.writeLegibly(out);
}
//Function to read a record from the input stream.
istream& readFromConsole(istream&);
/*Overload the operator >> to read fromo the input stream.*/
friend istream& operator>>(istream& in, Student& sr)
{
//Call the member function to read.
return sr.readFromConsole(in);
}
};
#endif
//student.cpp
//Include the header files.
#include "student.h"
//Constructor to initialize the variables.
Student::Student() : majorLen(10)
{
//Call base call constructor for initialization.
Personal();
//Create the character array for the major.
major = new char[majorLen+1];
}
//Constructor to initialize all the variables. This constructor takes arguments*/
Student::Student(char *ssn, char *n, char *c, int y, long s, char *m) :
majorLen(11)
{
//Call baseclass constructor.
Personal(ssn,n,c,y,s);
//Create the character array for the major.
major = new char[majorLen+1];
//Copy the major.
strcpy(major,m);
}
//Function to write the record to the output stream.
void Student::writeNullToFile(fstream& out)
{
/*Call base class method to write the name, city, SSN, year, salary.*/
Personal::writeNullToFile(out);
//Write the major.
out.write(major,majorLen);
}
//Function to write the record to the output stream.
void Student::writeToFile(fstream& out) const
{
/*Call base class method to write the name, city, SSN, year, salary.*/
Personal::writeToFile(out);
//Write the major.
out.write(major,majorLen);
}
//Function to read a record from the input stream.
void Student::readFromFile(fstream& in)
{
/*Call baseclass method to read the name,city, SSN, year,salary.*/
Personal::readFromFile(in);
//Read the major.
in.read(major,majorLen);
}
/*Function to write the student record to the output stream.*/
ostream& Student::writeLegibly(ostream& out)
{
/*Call baseclass method to write the name,city, SSN, year,salary.*/
Personal::writeLegibly(out);
major[majorLen] = '\0';
//Write the major.
out << ", major = " << major;
//Return the output stream.
return out;
}
//Function to read a record from the input stream console.
istream& Student::readFromConsole(istream& in)
{
/*Call base class method to read name, city, year, SSN, salary from console.*/
Personal::readFromConsole(in);
char s[80];
//Prompt the user to enter the major.
cout << "Major: ";
//read the major in variable 's'.
in.getline(s,80);
//Copy the major from 's'.
strncpy(major,s,9);
//Return the input stream.
return in;
}
//Function to check record is null.
bool Student::isNull()
{
//Call base class method to check the record is null.
return Personal::isNull();
}
//database.h
//Define the header file.
#ifndef DATABASE
#define DATABASE
//Create the template class.
template<class T>
//Create the class Database
class Database
{
//Access Specifier.
public:
//Construtor.
Database();
//Destructor
~Database();
/*Function that displays the menu and proceeds as per user wish.*/
void run();
//Access Specifier.
private:
/* Declare variables*/
fstream database;
char fName[20];
//Function to display the database
ostream& print(ostream&);
//Function to add a record into the database.
void add(T&);
/*Function to find a particular record in the database.*/
bool find(const T&);
//Function to modify the record in the database.
void modify(const T&);
//Function to delete the record from the database.
void remove(const T&);
/*Overloaded operator << to print the given database to the output stream.*/
friend ostream& operator<<(ostream& out, Database& db)
{
//Call the method to print the database.
return db.print(out);
}
};
#endif
//database.cpp
//Include the header files.
#include <iostream>
#include <vector>
#include "student.h"
#include "personal.h"
#include "database.h"
//No argumented constructor.
template<class T>
Database<T>::Database() {}
//Destructor
template<class T>
Database<T>::~Database()
{
//Declare the variables.
T tmp;
/*Create temporary file */
fstream tmpFile;
tmpFile.open("tmp1.txt",ios::in|ios::out|ios::binary|ios::trunc );
//Open the database.
database.open(fName,ios::in|ios::out|ios::binary);
/*Check database is null. If so exit from the loop.*/
if (database.eof())
//Exit from the loop.
exit(1);
/*Infinite loop that runs until record is inserted in the database.*/
while (true)
{
//Read a record from the file.
tmp.readFromFile(database);
/*Check database is null. If so exit from the loop.*/
if (database.eof())
//Exit from the loop.
break;
//Otherwise write record to the tmpFile.
else if(!tmp.isNull())
{
//write record to the tmpFile.
tmp.writeToFile(tmpFile);
}
}
//Close tmpFile
tmpFile.close();
//Close database
database.close();
//Open the database.
database.open("student.txt",ios::in|ios::out|ios::binary | ios::trunc );
//Open the tmp1.txt
tmpFile.open("tmp1.txt", ios::in| ios::out| ios::binary );
/*Inifinite loop that runs until record is inserted in the database.*/
while (true)
{
//Read a record from the file.
tmp.readFromFile(tmpFile);
/*Check tmpFile is null. If so exit from the loop.*/
if (tmpFile.eof())
//Exit from the loop.
break;
//Write the valid record to the file.
tmp.writeToFile(database);
}
//Close tmpFile
tmpFile.close();
//Close database
database.close();
//Rename the new file.
rename("tmp1.txt", fName);
}
//Function to add a record into the database.
template<class T>
void Database<T>::add(T& d)
{
//Open the database.
database.open(fName,ios::in|ios::out|ios::binary);
//Goto the file end.
database.seekp(0,ios::end);
//Write 'd' to the database.
d.writeToFile(database);
//Close the database.
database.close();
}
//Function to modify the existing record in the database.
template<class T>
void Database<T>::modify(const T& d)
{
//Declare the variable.
T tmp;
//Open the database.
database.open(fName,ios::in|ios::out|ios::binary);
//Repeated search until database is null.
while(!database.eof())
{
//Read the record from the database.
tmp.readFromFile(database);
//Check tmp matches d.
if (tmp == d)
{
//Read the record
cin >> tmp;
//Seek to the record's position.
database.seekp(-d.size(),ios::cur);
//Write the record to the file.
tmp.writeToFile(database);
//Close the database.
database.close();
//Exit from the function.
return;
}
}
//Close the database.
database.close();
//Print the message indicating record not found.
cout << "The record to be modified is not in the database\n";
}
//Function to modify the existing record in the database.
template<class T>
void Database<T>::remove(const T& d)
{
//Declare the variable.
T tmp;
//Open the database.
database.open(fName,ios::in|ios::out|ios::binary);
//Repeated search until database is null.
while(!database.eof())
{
//Read the record from the database.
tmp.readFromFile(database);
//Check tmp matches d.
if (tmp == d)
{
//Seek to the record's position.
database.seekp(-d.size(),ios::cur);
//Write the record to the file.
tmp.writeNullToFile(database);
//Close the database.
database.close();
//Exit from the function.
return;
}
}
//Close the database.
database.close();
//Print the message indicating record not found.
cout << "The record to be deleted is not in the database\n";
}
//Function to find the given record in the database.
template<class T>
bool Database<T>::find(const T& d)
{
//Declare the variable.
T tmp;
//Open the database.
database.open(fName,ios::in|ios::binary);
while(!database.eof())
{
//Read the record from the database.
tmp.readFromFile(database);
//Check tmp matches d.
if (tmp == d)
{
//Close the database.
database.close();
//Record found, so return true.
return true;
}
}
//Close the database.
database.close();
//Record not found, so return false.
return false;
}
template<class T>
ostream& Database<T>::print(ostream& out)
{
//Declare the variable.
T tmp;
//Open the database.
database.open(fName,ios::in|ios::binary);
//Infinite loop.
while (true)
{
//Read a record from the file.
tmp.readFromFile(database);
/*Check database is null. If so exit from the loop.*/
if (database.eof())
//Exit from the loop.
break;
//Write the record tmp to the output stream.
out << tmp << endl;
}
//Close the database.
database.close();
//Return the output stream.
return out;
}
//Function to process the user wish.
template<class T>
void Database<T>::run()
{
//Get the database filename.
cout << "File name: ";
cin >> fName;
//Declare variables.
char option[5];
T rec;
//Display menu.
cout << "1. Add 2. Find 3. Modify a record; 4. Remove a record 5. Exit\n";
//Get option.
cout << "Enter an option: ";
cin.getline(option,4);
//Infinite loop ends until user wishes to exit.
while (cin.getline(option,4))
{
//If user wants to add a record.
if (*option == '1')
{
//Get the record.
cin >> rec;
//Write the record into the database.
add(rec);
}
//If user wants to find a record,
else if (*option == '2')
{
//Read the SSN
rec.readKey();
//Display record is found or not.
cout << "The record is ";
//Check finding record returns false.
if (find(rec) == false)
cout << "not ";
cout << "in the database\n";
}
/*If user wants to modify a record in the database,*/
else if (*option == '3')
{
//Read the SSN of the record to be modified.
rec.readKey();
//Call the method modify()
modify(rec);
}
/*If user wants to remove a record in the database,*/
else if (*option == '4')
{
//Read the SSN of the record to be modified.
rec.readKey();
//Call the method remove()
remove(rec);
}
//If user enters wrong option.
else if (*option != '5')
//Print wrong input.
cout << "Wrong option\n";
//Otherwise exit from the loop.
else
//Return to the main function.
return;
//Display the database.
cout << *this;
//Ask the user for an option.
cout << "Enter an option: ";
}
}
//main() method.
int main()
{
/*Creating the database with Personal objects and call the function run().*/
Database<Personal>().run();
//To pause the console window.
system("pause");
return 0;
}
Output:
File name: student.txt
1. Add 2. Find 3. Modify a record; 4. Remove a record 5. Exit
Enter an option: 1
SSN: 101
Name: Arlen
City: Delhi
Birthyear: 2005
Salary: 80000
SSN = 101, name = Arlen, city = Delhi, year = 2005, salary = 80000
Enter an option: 1
SSN: 002
Name: Akash
City: Calcutta
Birthyear: 2001
Salary: 10000
SSN = 101, name = Arlen, city = Delhi, year = 2005, salary = 80000
SSN = 002, name = Akash, city = Calcutta, year = 2001, salary = 10000
Enter an option: 4
Enter SSN: 002
SSN = 101, name = Arlen, city = Delhi, year = 2005, salary = 80000
SSN = #02, name = Akash, city = Calcutta, year = 2001, salary = 10000
Enter an option: 5
Press any key to continue . . .
After running of the program, the file has been changed as follows,
student.txt:
Want to see more full solutions like this?
Chapter 1 Solutions
EBK DATA STRUCTURES AND ALGORITHMS IN C
- Modular Program Structure. Analysis of Structured Programming Examples. Ways to Reduce Coupling. Based on the given problem, create an algorithm and a block diagram, and write the program code: Function: y=xsinx Interval: [0,π] Requirements: Create a graph of the function. Show the coordinates (x and y). Choose your own scale and show it in the block diagram. Create a block diagram based on the algorithm. Write the program code in Python. Requirements: Each step in the block diagram must be clearly shown. The graph of the function must be drawn and saved (in PNG format). Write the code in a modular way (functions and the main part should be separate). Please explain and describe the results in detail.arrow_forwardBased on the given problem, create an algorithm and a block diagram, and write the program code: Function: y=xsinx Interval: [0,π] Requirements: Create a graph of the function. Show the coordinates (x and y). Choose your own scale and show it in the block diagram. Create a block diagram based on the algorithm. Write the program code in Python. Requirements: Each step in the block diagram must be clearly shown. The graph of the function must be drawn and saved (in PNG format). Write the code in a modular way (functions and the main part should be separate). Please explain and describe the results in detail.arrow_forwardBased on the given problem, create an algorithm and a block diagram, and write the program code: Function: y=xsinx Interval: [0,π] Requirements: Create a graph of the function. Show the coordinates (x and y). Choose your own scale and show it in the block diagram. Create a block diagram based on the algorithm. Write the program code in Python. Requirements: Each step in the block diagram must be clearly shown. The graph of the function must be drawn and saved (in PNG format). Write the code in a modular way (functions and the main part should be separate). Please explain and describe the results in detail.arrow_forward
- Question: Based on the given problem, create an algorithm and a block diagram, and write the program code: Function: y=xsinx Interval: [0,π] Requirements: Create a graph of the function. Show the coordinates (x and y). Choose your own scale and show it in the block diagram. Create a block diagram based on the algorithm. Write the program code in Python. Requirements: Each step in the block diagram must be clearly shown. The graph of the function must be drawn and saved (in PNG format). Write the code in a modular way (functions and the main part should be separate). Please explain and describe the results in detail.arrow_forward23:12 Chegg content://org.teleg + 5G 5G 80% New question A feed of 60 mol% methanol in water at 1 atm is to be separated by dislation into a liquid distilate containing 98 mol% methanol and a bottom containing 96 mol% water. Enthalpy and equilibrium data for the mixture at 1 atm are given in Table Q2 below. Ask an expert (a) Devise a procedure, using the enthalpy-concentration diagram, to determine the minimum number of equilibrium trays for the condition of total reflux and the required separation. Show individual equilibrium trays using the the lines. Comment on why the value is Independent of the food condition. Recent My stuff Mol% MeOH, Saturated vapour Table Q2 Methanol-water vapour liquid equilibrium and enthalpy data for 1 atm Enthalpy above C˚C Equilibrium dala Mol% MeOH in Saturated liquid TC kJ mol T. "Chk kot) Liquid T, "C 0.0 100.0 48.195 100.0 7.536 0.0 0.0 100.0 5.0 90.9 47,730 928 7,141 2.0 13.4 96.4 Perks 10.0 97.7 47,311 87.7 8,862 4.0 23.0 93.5 16.0 96.2 46,892 84.4…arrow_forwardYou are working with a database table that contains customer data. The table includes columns about customer location such as city, state, and country. You want to retrieve the first 3 letters of each country name. You decide to use the SUBSTR function to retrieve the first 3 letters of each country name, and use the AS command to store the result in a new column called new_country. You write the SQL query below. Add a statement to your SQL query that will retrieve the first 3 letters of each country name and store the result in a new column as new_country.arrow_forward
- We are considering the RSA encryption scheme. The involved numbers are small, so the communication is insecure. Alice's public key (n,public_key) is (247,7). A code breaker manages to factories 247 = 13 x 19 Determine Alice's secret key. To solve the problem, you need not use the extended Euclid algorithm, but you may assume that her private key is one of the following numbers 31,35,55,59,77,89.arrow_forwardConsider the following Turing Machine (TM). Does the TM halt if it begins on the empty tape? If it halts, after how many steps? Does the TM halt if it begins on a tape that contains a single letter A followed by blanks? Justify your answer.arrow_forwardPllleasassseee ssiiirrrr soolveee thissssss questionnnnnnnarrow_forward
- C++ Programming: From Problem Analysis to Program...Computer ScienceISBN:9781337102087Author:D. S. MalikPublisher:Cengage LearningC++ for Engineers and ScientistsComputer ScienceISBN:9781133187844Author:Bronson, Gary J.Publisher:Course Technology PtrProgramming Logic & Design ComprehensiveComputer ScienceISBN:9781337669405Author:FARRELLPublisher:Cengage
- Microsoft Visual C#Computer ScienceISBN:9781337102100Author:Joyce, Farrell.Publisher:Cengage Learning,New Perspectives on HTML5, CSS3, and JavaScriptComputer ScienceISBN:9781305503922Author:Patrick M. CareyPublisher:Cengage LearningSystems ArchitectureComputer ScienceISBN:9781305080195Author:Stephen D. BurdPublisher:Cengage Learning