1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64
|
#include "hardware.h"
#include <iostream>
#include <fstream>
using namespace std;
void createfile(const string & fname, int n);
void fill(const string & fname);
int main()
{
cout << "size: " << sizeof(Hardware) << endl;
string filename = "records.dat";
createfile(filename, 100);
fill(filename);
return 0;
}
void createfile(const string & fname, int n)
{
ofstream fout(fname.c_str(), ios::binary);
Hardware record;
for (int i=0; i<n; i++)
{
fout.write( reinterpret_cast<const char *>(&record), sizeof(record) );
}
}
void fill(const string & fname)
{
// test data automatically entered in file
// arrays to store test data
const int num = 8; // number of entries
Hardware records; // constructor zeros out each data member
int recordArray[num] = { 3, 17, 24, 39, 56, 68, 77, 83 };
string toolNameArray[num] = { "Electric sander ", "Hammer", "Jig saw", "Lawn mower",
"Power saw", "Screwdriver", "Sledge hammer", "Wrench" };
int quantityArray[num] = { 7, 76, 21, 3, 18, 106, 11, 34 };
double costArray[num] = { 57.98, 11.99, 11.00, 79.50, 99.99, 6.99, 21.50, 7.50 };
fstream outRecord(fname.c_str(), ios::in | ios::out | ios::binary);
// output test data to file
for (int i = 0; i < num; ++i)
{
records.setRecordNumber(recordArray[i]);
records.setToolName(toolNameArray[i]);
records.setQuantity(quantityArray[i]);
records.setCost(costArray[i]);
// seek position to output data
outRecord.seekp((records.getRecordNumber() - 1) * sizeof(Hardware));
// write user input into file
outRecord.write(reinterpret_cast<const char*>(&records), sizeof(records));
}
}
|