2016-04-27 59 views
1

我一直在試圖寫這個到一個文件,但無濟於事,我找到了一種方法,我也需要能夠讀取這個。這裏是結構將一個包含另一個向量的結構向量寫入二進制文件

struct details 
{ 
    float balance=0; 
    vector<string> history; 
    string pin; 
}; 
struct customer 
{ 
    int vectorID; 
    string name; 
    char type; 
    details detail; 
}; 
vector<customer> accounts; 

我有什麼現在的問題是:

ofstream fileBack; 
fileBack.open("file.txt", ios::in|ios::binary|ios::trunc); 

fileBack.write(reinterpret_cast<char*>(&accounts), accounts.size()*sizeof(accounts)); 
fileBack.close(); 

而且我知道這是錯誤的,因爲當我打開文件時,它是幾乎沒有大到足以容納我投入的信息它。 所有幫助表示感謝,提前謝謝

+0

您找到了錯誤的方法。 – LogicStuff

+0

是的,我想,我剛剛在黑暗中拍攝希望東西棒 – Lansrow

回答

1

一個非常簡單的方法是使用Boost Serialization。你需要在每個類來定義一個成員函數來處理,例如序列化:

void details::serialize(Archive & ar, const unsigned int version) { 
    ar & balance; 
    ar & history; 
    ar & pin; 
} 


void customer::serialize(Archive & ar, const unsigned int version) { 
    ar & vectorID; 
    ar & name; 
    ar & type; 
    ar & detail; 
} 

然後,當您要添加到文件,你可以這樣做:

std::ofstream ofs("filename", std::ios::binary); // binary file open 
.... 
// save data to archive 
{ 
    boost::archive::text_oarchive oa(ofs); 
    // write class instance to archive 
    oa << yourCustomerClass; 
} 

並且對方閱讀文件。

+0

謝謝!我會嘗試並實現這一點,並取回我的結果 – Lansrow

相關問題