【发布时间】:2014-01-03 04:56:17
【问题描述】:
我正在尝试写入二进制文件,这是我的 sn-p 代码
#include <iostream>
#include <fstream>
#include <string>
using namespace std;
struct user
{
string ID;
string password;
};
int main()
{
fstream afile;
afile.open("user.dat",ios::out|ios::binary);
user person;
person.ID ="001";
person.password ="abc";
afile.write (reinterpret_cast <const char *>(&person), sizeof (person));
person.ID ="002";
person.password ="def";
afile.write (reinterpret_cast <const char *>(&person), sizeof (person));
afile.close();
afile.open("user.dat",ios::in|ios::binary);
while (afile.read (reinterpret_cast <char *>(&person), sizeof (person)))
{
cout<<person.ID
<<" "
<<person.password
<<endl;
}
}
我希望我的控制台输出是
001 abc
002 def
相反,我得到了
002 def
002 def
谁能给我解释一下?
【问题讨论】:
-
在完成文件后关闭文件总是一个好主意,例如第二次打开
afile。 -
@JonnyHenly,析构函数将其关闭。
-
这行不通。
std::string不是普通的旧数据对象,您不能以这种方式将它们转储到文件中或从文件中转储。改为查看序列化。 -
请注意
std::string内部有一个指针,您正在写入和读取该指针,而不是字符串。
标签: c++ debugging file-io binary binaryfiles