Code:
//Program #14 Writing Structs to Files, Thomas Eding CS265-8051
#include <cstdlib>
#include <fstream>
#include <iostream>
using namespace std;
struct Record {
char name[15];
double amt;
}
void printRecord(const Record &r) {
cout << "Name: " << r.name << "\nAmount: " << r.amt << "\n";
}
int main() {
Record master[10] = {{"Helen", 10}, {"Julie", 20}, {"Lena", 30}, {"Alan", 40}, {"Annie", 50}, {"May", 60}, {"Lee", 70}, {"Sam", 80}, {"June", 90}, {"Bill", 100}};
Record trans[7] = {{"Lena", 10}, {"Julie", 5.75}, {"Lee", 15.02}, {"Ed", 40}, {"Julie", 10}, {"Art", 5}, {"Bill", 7.32}};
ofstream fout;
fout.open("master.dat", ios::binary);
for(int i=0; i<10; ++i) fout.write((char*) &master[i], sizeof(Record));
fout.close();
fout.open("trans.dat", ios::binary);
for(int i=0; i<7; ++i) fout.write((char*) &trans[i], sizeof(Record));
fout.close();
Record temp;
ifstream fin;
fin.open("master.dat", ios::binary);
cout << "master.dat records:\n\n";
for(int i=0; i<10; ++i) {
fin.read((char*) &temp, sizeof(Record));
printRecord(temp);
}
fin.close();
fin.open("trans.dat", ios::binary);
cout << "trans.dat records:\n\n";
for(int i=0; i<7; ++i) {
fin.read((char*) &temp, sizeof(Record));
printRecord(temp);
}
fin.close();
return 0;
}
Bookmarks