最近、Ubuntuを最近使い始めました。 私はいくつかのデータを保存し、後でそこから読み戻すことができる非常にシンプルなプログラムを構築しています。Ubuntuの.datファイルや.binファイルを読み取れません "セグメンテーションフォールト(コアダンプ)"
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でない場合は、あなたのバグがあります。 –
あります。実際のプログラムで。私の間違いはここにある。おっと – poh
「レコード」の種類は何ですか?それにはいくつかの[vtable](https://en.wikipedia.org/wiki/Virtual_method_table)、あるいはいくつかの(内部または内部の)ポインタがありますか? **あなたのコードには[未定義の動作](https://en.wikipedia.org/wiki/Undefined_behavior)**がありますので、Linux上でクラッシュすることは幸運です(Windows上では動作すると思われます) .... –