Binary Read and Write
Dec 5, 2011 at 12:19am UTC
I have to create a program that creates a binary file using a 25 data structures then a second one that reads in the binary data file and decodes it and outputs it. But I seem to be experiencing a problem that I don't know how to fix. Either something isn't right with my reading or writing but I can't figure out what. Here's my code:
Program that creates the binary file
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
#include <iostream>
#include <fstream>
using namespace std;
struct FileRec
{
int employeeNum;
char employeeName[21];
double hourlyRate, hoursWorked;
};
int main()
{
ifstream in("input.txt" );
FileRec employee;
fstream binout;
binout.open("binout.bin" , ios::binary | ios::out);
for (int k = 0; k < 26; k++)
{
in>>employee.employeeNum;
in.getline(employee.employeeName, 21);
in>>employee.hourlyRate;
in>>employee.hoursWorked;
binout.write(reinterpret_cast <char *>(&employee), sizeof (employee));
}
return 0;
}
And the program that reads in binary and outputs regular text:
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
#include <iostream>
#include <fstream>
#include <iomanip>
using namespace std;
struct FileRec
{
int employeeNum;
char employeeName[21];
double hourlyRate, hoursWorked;
};
int main()
{
FileRec employee;
fstream file;
file.open("binout.bin" , ios::binary | ios::in);
ofstream out("finaloutput.txt" );
out<<"Report #1: Data in Sequential Order" <<endl<<endl;
out<<left<<setw(9)<<"Record" <<setw(11)<<"Employee" ;
out<<setw(23)<<"Employee" <<setw(9)<<"Hourly" ;
out<<setw(5)<<"Hours" <<endl;
out<<left<<setw(10)<<"Number" <<setw(10)<<"Number" ;
out<<setw(24)<<"Name" <<setw(7)<<"Rate" ;
out<<setw(6)<<"Worked" <<endl;
for (int k = 1; k < 26; k++)
{
file.read(reinterpret_cast <char *>(&employee), sizeof (employee));
out<<" " <<left<<setw(2)<<k<<right<<setw(12)<<employee.employeeNum;
out<<" " <<left<<setw(20)<<employee.employeeName;
out<<" " <<setw(5)<<fixed<<setprecision(2)<<employee.hourlyRate;
out<<" " <<setw(5)<<employee.hoursWorked<<endl;
}
return 0;
}
Here's a sample of that the output looks like:
Report #1: Data in Sequential Order
Record Employee Employee Hourly Hours
Number Number Name Rate Worked
1 21434 0.00 0.00
2 21434 0.00 0.00
..and so on 25 times.
The first employee's number is 21434,so its partially working, but for the life of me I can't figure out what's wrong. any pointers?
Thanks,
Nick
Dec 5, 2011 at 12:33am UTC
In the program that reads from the file you start the loop at k=1.
Last edited on Dec 5, 2011 at 12:34am UTC
Dec 5, 2011 at 12:37am UTC
Simply so I can use it to keep count of the record number. The program does the same thing when it starts at 0
Topic archived. No new replies allowed.