-
reading binary file
I got the program in my last thread working, now I'm trying to get a program to read the binary file which it created in the last one. My only problem is that it won't read. At all.
NOTE:
I'm working on an old compiler. Saying 'put functions here blahblah' 'dont use.h' doesnt help at all, currently the code below compiles, there are 0 syntax errors.
Code:
#include <fstream.h>
#include <stdlib.h>
struct employee
{
int id;
int salary;
char firstname[11];
char lastname[11];
};
int main (void)
{
fstream fsbin,
fout;
fsbin.open("hwk07.bin", ios::in);
fout.open("hwk07out.txt", ios::out);
void readwritebin (fstream&, fstream&);
readwritebin (fsbin, fout);
return 0;
}
void readwritebin (fstream& fsbin, fstream& fout)
{
employee worker = {0},
labor[100] = {0};
int idNum = 1;
while (idNum != 0)
{
char id[4];
cout << "\nPlease enter an id number, or '0' to exit: ";
cin >> idNum;
if (idNum != 0)
{
fsbin.seekg(idNum * sizeof(employee), ios::beg);
fsbin.read((char*)&worker.id, sizeof(int));
cout << "\nThe data for employee " << idNum << "is: \n"
<< worker.id << "\t" << worker.firstname << "\t"
<< worker.lastname << "\t" << worker.salary << "\t"
<< (worker.salary / 12.0) << "\n";
} //if
} // while
} // readwritebin
-
Are you saying that puting this function prototype outside before the main won't fix anything?
void readwritebin (fstream&, fstream&);
-
I just glanced at your code. First of all you need to open the binary file in binary mode. The default mode is text. Use the flag ios::binary. You can have multiple flags together by or'ing them. For example:
ios::binary | ios::out
Also, take out the function prototype from within your main function. Place this above main like so:
Code:
#include <fstream.h>
#include <stdlib.h>
struct employee
{
int id;
int salary;
char firstname[11];
char lastname[11];
};
// Function Prototypes here:
void readwritebin (fsbin, fout);
int main (void)
{
fstream fsbin,
fout;
.
.
.
-
Like I said in the first part, I'm on an old compiler, putting the declaration outside main WILL NOT DO ANYTHING. I have 0 syntax errors. Its not reading when I use fsbin.read. Also my compiler already uses ios::binary.
-
Code:
#include <fstream.h>
#include <stdlib.h>
struct UPGRADE
{
int TwoWeeksSalary;
char Ebay;
char FedEx
};
does this help?
:p
-
Code:
fsbin.read((char*)&worker.id, sizeof(int));
cout << "\nThe data for employee " << idNum << "is: \n"
<< worker.id << "\t" << worker.firstname << "\t"
<< worker.lastname << "\t" << worker.salary << "\t"
<< (worker.salary / 12.0) << "\n";
You're only reading in a single int(the id) and then expecting the other members of the employee struct to be valid.
Possibly, you want to read in the entire structure?
Code:
fsbin.read((char*) &worker, sizeof(worker));