因此,我剛剛開始使用Ubuntu。 我正在構建這個非常簡單的程序,它可以讓我存儲一些數據並在稍後讀回。無法讀取Ubuntu中的.dat或.bin文件「Segmentation fault(核心轉儲)」
使用C++,fstream,一些對象存儲在.dat文件中。
// function to store
void storeRecord(Record r){
fstream afile;
afile.open("file.dat" , ios::out | ios::binary | ios::app);
afile.write(reinterpret_cast <const char*> (&r), sizeof(r));
afile.close();
}
但當我嘗試(調用查詢()函數)從同一個文件中讀取,我得到「分割故障(核心轉儲)」
void query(){
Record r;
fstream afile;
afile.open("file.dat", ios::in | ios::binary);
while(afile.read(reinterpret_cast <char*> (&r), sizeof(r))){
// do something
}
afile.close();
}
這用來工作在窗戶上。這是爲什麼?
#include <iostream>
#include <string>
#include <fstream>
using namespace std;
class Record{
public:
// Constructors
Record();
Record(string accountID, string name, string deptID, string password, int role);
~Record();
// Assessors and Mutators
string getAccountID();
string getName();
string getDeptID();
string getPW();
int getRole();
void setAccountID(string accountID);
void setName(string name);
void setDeptID(string deptID);
void setPW(string PW);
void setRole(int role);
// Other functions
string toString();
private:
string accountID;
string name;
string deptID;
string password;
int role; // normal user, HR personal, admin
};
在查詢中沒有定義r。什麼是記錄?如果它不是POD,那麼你有bug。 – 2017-10-17 17:39:44
有。在實際的程序中。我的錯誤在這裏。 oops – poh
「Record」的類型是什麼?它是否有一些[vtable](https://en.wikipedia.org/wiki/Virtual_method_table)或一些(甚至是不正確的或內部的)指針? **你的代碼有[未定義的行爲](https://en.wikipedia.org/wiki/Undefined_behavior)**,所以你很幸運,它在Linux上崩潰(並且*不幸*它出現在Windows上) .... –