|
ex8-12.cpp - Example 8-12 File I/O - read() and write() |
// File: ex8-12.cpp - File I/O read() and write()
#include <fstream>
#include <iostream>
#include <iomanip>
#include <cstdlib>
#include <cstring>
#include <string>
using namespace std;
class Employee
{
public:
Employee() : age(0), salary(0.f) {}
private:
char empno[8];
char name[32];
unsigned short age;
float salary;
friend istream& operator>>(istream&, Employee&);
friend ostream& operator<<(ostream&, const Employee&);
};
istream& operator>>(istream& in, Employee& E)
{
in >> E.empno >> E.name >> E.age >> E.salary;
return in;
}
ostream& operator<<(ostream& out, const Employee& E)
{
out << setprecision(2) << fixed << showpoint << left;
out << setw(8) << E.empno
<< setw(13) << E.name
<< right << setw(3) << E.age
<< setw(10) << E.salary;
return out;
}
class EmployeeFile
{
public:
EmployeeFile(string filename = "empfile");
void print(); // Why not const?
void open_for_read_write();
void close() { File.close(); }
bool operator!() const { return !File.rdstate(); }
private:
string Filename;
fstream File;
friend EmployeeFile& operator>>(EmployeeFile&, Employee&);
friend EmployeeFile& operator<<(EmployeeFile&, const Employee&);
};
EmployeeFile::EmployeeFile(string filename)
: Filename(filename), File(filename.c_str(),ios::out|ios::binary)
{
}
void EmployeeFile::print()
{
Employee temp;
// position to the beginning of the file
File.seekg(0,ios_base::beg);
// read data from the file and print out each Employee record
while (!(*this>>temp)) {
cout << temp << endl;
}
// clear the File stream state (after reading EOF)
File.clear();
}
void EmployeeFile::open_for_read_write()
{
File.open(Filename.c_str(),ios::in | ios::out | ios::binary);
if (File.fail() ) {
cerr << "Unable to open Employee file: " << Filename << endl;
exit(-1);
}
}
EmployeeFile& operator>>(EmployeeFile& EF, Employee& E)
{
EF.File.read((char*) &E, sizeof E);
return EF;
}
EmployeeFile& operator<<(EmployeeFile& EF, const Employee& E)
{
EF.File.write((char*) &E, sizeof E);
return EF;
}
int main()
{
Employee temp;
EmployeeFile EmpFile("employee.dat");
for (int i = 0; i<4; ++i) {
cout << "Enter empno name age salary\n";
cin >> temp;
EmpFile << temp;
}
// close the file and reopen it in read-write mode
EmpFile.close();
EmpFile.open_for_read_write();
EmpFile.print();
return 0;
}
CIS27: Programming in C++ Instructor: Joe Bentley