c++ - Binary files with Struct, classes, fstream error -
i have question regarding assignment have.
here have 2 of classes, employee class , gm class
void gm::addemployee(fstream& afile, int noofrecords) { afile.open("employeeinfo.dat", ios::in | ios::binary); employee::einfo e; employee emp; char name[80]; cout << "\nadd employee info" << endl; cout << "---------------------" << endl; cout << "new employee username: "; cin.clear(); cin.ignore(100, '\n'); cin.getline(name, 80); //check if there entry inside file name. //if yes, add fail bool flag = true; if(noofrecords > 0) { for(int i=1; i<=noofrecords; i++) { afile.read (reinterpret_cast <char *>(&e), sizeof(e)); if(!strcmp(name, e.username)) { cout << "username used, add gm failed" << endl; flag = false; } } } afile.close(); if(flag) { //open in appending mode afile.open("employeeinfo.dat", ios::out | ios::app | ios::binary); strcpy(e.username, name); cout << "please enter new employee's password: "; cin.getline(e.password, 80); cout << "\nplease enter new employee's appointment " << "\n(0 = gm / 1 = hm / " << "2= bs / 3 = fos)\n : "; cin >> e.eid; cin.clear(); cin.ignore(100, '\n'); emp.dist = strlen(e.password); emp.caesar_encrypt(e.password, 3, emp.dist); afile.write(reinterpret_cast <const char *>(&e), sizeof(e)); afile.close(); cout << "\nemployee added" << endl; } }
the above function gm class, add employees.
i have declared structure in employee class as
struct einfo { char username [80]; char password [80]; int eid; };
the problem way of doing, when try add employee employeeinfo.dat data disappears. becomes blank after used add employee function.
can guide me on did wrong?
this wrong way read data e
:
afile.read(reinterpret_cast<char*>(&e), sizeof(e));
likewise, wrong way write data e
:
afile.write(reinterpret_cast<const char*>(&e), sizeof(e));
if need print or read data members of e
, need 1 @ time. moreover, using read
/write
in context unecessary because use extractor , inserter:
afile >> e.username; // ... afile << e.username << e.password;
Comments
Post a Comment