2014-02-06 46 views
0

我有一個關於我有任務的問題。結構,類,fstream錯誤的二進制文件

在這裏,我有課,員工類和通用類

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 is already an entry inside the file with this 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 is 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; 
     } 

} 

的2以上是從我的通用類,這是增加員工的功能。

我已經宣佈在Employee類的構造,

struct eInfo 
{ 
    char username [80]; 
    char password [80]; 
    int eid; 
}; 

用做這種方式的問題是,當我嘗試添加員工 我EmployeeInfo.dat數據消失。我使用添加員工功能後,所有內容都變爲空白。

任何人都可以指導我,我做錯了什麼?

回答

0

這是讀取數據錯誤的方式進入e

afile.read(reinterpret_cast<char*>(&e), sizeof(e)); 

同樣的,這是從e寫入數據的錯誤的方式:

afile.write(reinterpret_cast<const char*>(&e), sizeof(e)); 

如果您需要打印或閱讀的數據成員,你需要一次一個這樣做。此外,在這種情況下使用read/write是不必要的,因爲你只需使用提取和插入:

afile >> e.username; 
// ... 
afile << e.username << e.password; 
+0

我不精通C,但它是必要的å文件對象傳遞給這個功能呢? – bf2020

+0

@ bf2020是否需要將'afile'傳遞給* what *函數?對不起,我似乎沒有遵循...順便說一句,這是* C++ *。 – 0x499602D2

+0

不要擔心,這是我沒有跟着...我的一個壞問題。我不知道_C++ _,並且被第一行使用的'::'所困惑。我會閱讀它。 – bf2020

相關問題