Lab 12, FA20-BEE-224
Lab 12, FA20-BEE-224
Program:- Description:-
#include <fstream> Explanation
#include <iostream> Defining payfile as an input file:
#include <iomanip>
using namespace std; The line ifstream payfile; defines payfile as an
input file stream.
int main() {
// Define payfile as an input file Opening payfile and attaching it to payroll.dat:
ifstream payfile;
The line payfile.open("payroll.dat"); opens the file
float gross; named payroll.dat.
float net;
float hours; Checking if payfile does not exist:
float payRate;
float stateTax; The condition if (!payfile) checks if the file could
float fedTax; not be opened,
cout << fixed << setprecision(2) << showpoint; indicating that it might not exist.
// Open payfile and attach it to the physical file Priming the read for the payfile:
named payroll.dat
payfile.open("payroll.dat"); The line payfile >> hours >> payRate >> stateTax
>> fedTax;
// Check if payfile does not exist
if (!payfile) { reads the first set of values from the file.
cout << "Error opening file. \n";
cout << "It may not exist where indicated" Loop condition to run while payfile has more
<< endl; data:
return 1;
} The while (payfile) loop continues processing as
long as there are more data to read.
cout << "Pay Rate" << setw(10) << "Hours" <<
setw(15) << "Gross Pay" << setw(12) << "Net Calculating gross and net pay:
Pay" << endl << endl;
Inside the loop, gross = payRate * hours;
// Prime the read for the payfile
payfile >> hours >> payRate >> stateTax >> and net = gross - (gross * stateTax) - (gross *
fedTax; fedTax); calculate the gross and net pay,
respectively.
// Loop while payfile has more data to process
while (payfile) { Reading the next set of values:
gross = payRate * hours;
net = gross - (gross * stateTax) - (gross * The line payfile >> hours >> payRate >> stateTax
fedTax); >> fedTax; inside the loop primes the next read
cout << payRate << setw(10) << hours << operation.
setw(15) << gross << setw(12) << net << endl; This program reads the payroll.dat file, processes
each employee's data, and outputs their pay
// Read the next set of values from the file information, handling any issues with file
payfile >> hours >> payRate >> stateTax >> existence.
fedTax;
}
payfile.close();
return 0;
}
Output:-
Task #2
Program:- Description:-
#include <fstream>
#include <iostream> Explanation of Changes
#include <iomanip>
using namespace std; Output File Stream: Added ofstream
payfile.close();
outfile.close();
return 0;
}
Output:-
Pay Rate Hours Gross Pay Net Pay
15.00 40 600.00 492.00
10.00 50 500.00 420.00
12.50 60 750.00 615.00
Task # 3
Program:- Description:-
#include <iostream>
#include <iomanip> Explanation
#include <fstream> readit Function:
using namespace std;
This function reads records from the input file and
const int NAMESIZE = 15; stores them in the array of Grades structures
const int MAXRECORDS = 50; (gradeType).
typedef Grades gradeType[MAXRECORDS]; Inside the function, a while loop reads each record
from the file and stores it in the
void readit(ifstream& infile, gradeType records,
int& numRecords); corresponding element of the array.
return 0;
}
Output:-
Home Task # 1:-
Program:- Description:-
#include <iostream>
#include <iomanip> Explanation
#include <fstream> New Field letter:
using namespace std;
A new field letter of type char is added to the
const int NAMESIZE = 15; Grades structure to store the letter grade.
const int MAXRECORDS = 50;
calculateLetterGrade Function:
struct Grades {
char name[NAMESIZE + 1]; This function takes the test scores and final exam
int test1; score as parameters and calculates the average
int test2;
int final; grade using the specified weights (30% for each
char letter; // New field to hold the letter grade test and 40% for the final).
};
It then determines the letter grade based on the
typedef Grades gradeType[MAXRECORDS]; average and returns it.
void readit(ifstream& infile, gradeType records, Updating readit Function: After reading each
int& numRecords); record from the file,
char calculateLetterGrade(int test1, int test2, int
final); the calculateLetterGrade function is called to
determine the letter grade, which is then assigned
int main() { to the letter field of the Grades structure.
ifstream indata;
indata.open("graderoll.dat"); Output Formatting:
int numRecord;
gradeType studentRecord; The output is updated to include the new letter
field,
if (!indata) {
cout << "Error opening file. \n"; which displays the letter grade corresponding to
cout << "It may not exist where indicated" each student's average grade.
<< endl;
return 1;
}
return 0;
}
Output:-
Task # 2
Program:- Description:-
#include <fstream> This C++ program, named "budget.cpp", is
#include <iostream> designed to manage financial information for
#include <iomanip> individuals. Here's a breakdown of its
using namespace std; functionality:
const int NAMESIZE = 15; 1. Header Files: The program includes necessary
header files like `<fstream>` for file handling,
struct budget { `<iostream>` for standard input-output operations,
char name[NAMESIZE + 1]; and `<iomanip>` for setting output formatting.
float income; // person's monthly income
float rent; // person's monthly rent 2. Constants and Structure Definition:
float food; // person's monthly food bill - `NAMESIZE` is defined as 15, representing
float utilities; // person's monthly utility bill the maximum size of a person's name.
float miscell; // person's other bills - The `budget` structure is defined to hold
float net; // person's net money after bills financial information, including name, income,
are paid rent, food costs, utilities, miscellaneous expenses,
}; and net income.
// READ THE RECORD FROM FILE AND This program essentially acts as a data entry tool
PLACE IT IN THE person RECORD for recording financial information, stores this
indata.read(reinterpret_cast<char*>(&person), data in a binary file,
sizeof(person));
retrieves it, and then formats and outputs it to a
// write information to output file text file for further analysis or reporting.
outdata << setw(20) << "Name" << setw(10)
<< "Income" << setw(10) << "Rent"
<< setw(10) << "Food" << setw(15) <<
"Utilities" << setw(15)
<< "Miscellaneous" << setw(10) << "Net
Money" << endl << endl;
outdata << setw(20) << person.name <<
setw(10) << person.income << setw(10) <<
person.rent
<< setw(10) << person.food << setw(15)
<< person.utilities << setw(15)
<< person.miscell << setw(10) <<
person.net << endl;
return 0;
}
Output:-
Task # 3
Program:- Description:-
# Function to read records from the keyboard Sure, here's a description of the provided code:
def read_records():
records = [] 1. Reading Records from Keyboard
while True: (`read_records`):
first_name = input("Person's First Name: ") - This function prompts the user to input
last_name = input("Person's Last Name: ") information for each field of a record.
street = input("Street: ") - It collects this information and appends it to a
city = input("City: ") list of records.
state = input("State: ") - The function continues to prompt the user until
zip_code = input("Zip: ") they indicate they don't want to input more data.
records.append((first_name.ljust(15),
last_name.ljust(15), street.ljust(30), city.ljust(20), 2. Writing Records to Binary File
state.ljust(5), zip_code)) (`write_to_binary`):
more_data = input("Enter Y if you would like - This function takes a list of records as input
to input more data: ") and writes each record to a binary file.
if more_data.upper() != 'Y': - Each field of the record is converted to bytes
break and written to the file.
return records - For the zip code, it's converted to a 32-bit
integer before being written to the file.
# Function to write records to a binary file
def write_to_binary(records): 3. Reading Records from Binary File
with open("records.bin", "wb") as f: (`read_from_binary`):
for record in records: - This function reads records from a binary file.
for field in record[:-1]: # Write all fields - It calculates the number of records in the file
except the last one (zip code) by dividing the total file size by the size of each
f.write(field.encode()) record.
f.write(int(record[-1]).to_bytes(4, - Then, it iterates over each record in the file.
byteorder='big')) # Write the zip code as a 32-bit - It seeks to the appropriate position from the
integer end of the file to read each record.
- Each field of the record is extracted from the
# Function to read records from a binary file bytes read, and the zip code is converted back
def read_from_binary(): from bytes to an integer.
records = []
with open("records.bin", "rb") as f: 4. Writing Records to Text File (`write_to_text`):
file_size = f.seek(0, 2) # Get the size of the - This function takes a list of records as input
file and writes them to a text file.
record_size = 86 # Size of each record - It formats each record to align the fields
num_records = file_size // record_size # properly in a tabular format and writes them to the
Calculate the number of records file.
for i in range(num_records):
f.seek(-((i + 1) * record_size), 2) # Move 5. Main Program:
the pointer to the beginning of the i-th record from - In the main program, it first reads records from
the end of the file the keyboard using `read_records`.
data = f.read(record_size) # Read the i-th - Then it writes these records to a binary file
record using `write_to_binary`.
first_name = data[:15].decode().rstrip() - After that, it reads the records back from the
last_name = data[15:30].decode().rstrip() binary file using `read_from_binary`.
street = data[30:60].decode().rstrip() - Finally, it writes these records to a text file
city = data[60:80].decode().rstrip() using `write_to_text`.
state = data[80:85].decode().rstrip()
zip_code = int.from_bytes(data[85:], 'big') Overall, this code allows the user to input records
# Read zip code as a 32-bit integer from the keyboard, stores them in a binary file,
records.append((first_name, last_name, retrieves them from the binary file, and then
street, city, state, zip_code)) writes them to a text file in a formatted manner.
return records
# Main program
if __name__ == "__main__":
records = read_records()
write_to_binary(records)
records = read_from_binary()
write_to_text(records)
print("Data written to records.txt")
Conclusion:-
The provided code implements a program that manages records of individuals, allowing users to input
data from the keyboard, store it in a binary file, read it back, and then write it to a text file. The input
process is structured, prompting users for each field of a record, ensuring consistent formatting. Records
are stored in a binary file using fixed-size fields, with the zip code converted to a 32-bit integer for
storage efficiency. Reading from the binary file is implemented to retrieve records from the end,
calculating the file's size and record size to determine the correct position. The retrieved records are then
processed and written to a text file, formatted in a tabular manner for readability. Overall, the program
provides a robust way to manage and manipulate records, offering flexibility in data input, efficient
storage in binary format, and clear presentation in the output text file.