[英]c++ read and write struct array with std::string into binary file
[英]Read and write structure containing std::string to .dat file using std::write and std::read C++
我有一個結構
struct details
{
std::string username;
std::string password;
bool isActive;
};
struct details v_Details;
我希望將這些數據寫入文件,然后在代碼的其他位置讀取它,以存儲詳細信息。 我試過使用std :: write似乎做的工作
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();
}
任何可以幫助我並為此提供解決方案的人。
當成員的大小不固定時,您不能直接編寫該對象並期望它正確存儲所有內容。 如果它是char
數組,則可以使用這種方式。
在這種情況下,我會先手動寫入詳細信息,例如username
長度,然后在username
寫入字符,以便在讀取時可以讀取用戶名的長度並從文件中讀取該字符數。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.