2014-02-14 45 views
0

我有一個結構讀取和含有的std :: string使用std成.dat文件寫入結構::寫和std ::讀C++

struct details 
{ 
    std::string username; 
    std::string password; 
    bool isActive; 
}; 

struct details v_Details; 

我希望把這些數據寫入到一個文件中,然後讀它在代碼中的某些其他位置作爲存儲細節的手段。我一直在使用的std ::寫這似乎做的工作

std::ofstream out_file; 
out_file.open ("db.dat" , ios::out | ios::binary) 
out_file.write((char*)&v_details , sizeof (struct details)) 

但是當我嘗試讀取它只能讀取用戶名和密碼的數據,然後它崩潰嘗試。

我的代碼讀取部分如下

std::ifstream in_file; 
in_file.open (fileName.c_str() , std::ifstream::in); 

std::string readFileLine = "\0"; 

if (in_file.is_open()) 
{ 
    do 
    { 
     in_file.read ((char*)&details , sizeof(details)); 
     cout << "\nDEBUG message-> " << __FILE__ <<" : " << __func__ << " : " << __LINE__ << " : Read - "<< details.username << " " << details.password << " " << isActive ; 
    }while (!in_file.eof()); 

in_file.close(); 
} 

如果誰能夠提供幫助和我在此修復。

+0

你必須記住,std :: string實例的內容實際上並不是它所包裝的字符串,但可能只是一個指向字符串的指針和它的長度。你應該閱讀[marshalling](http://en.wikipedia.org/wiki/Marshalling_%28computer_science%29)和[serialization](http://en.wikipedia.org/wiki/Serialization)。 –

+1

另請閱讀[Boost序列化庫](http://www.boost.org/doc/libs/1_55_0/libs/serialization/doc/index.html),它將幫助您處理這樣的事情。 –

回答

0

當你有沒有固定大小的成員時,你不能直接寫對象,並期望它正確地存儲所有東西。 如果它是char數組,您可以使用這種方法。

鑑於這種情況,我將手動編寫的細節,像username長度,再寫入字符username,這樣在閱讀我可以讀取用戶名的長度,從文件讀取的字符數。

相關問題