调试读/写字符串到二进制文件
我正在尝试写入二进制文件,这是我的代码片段
I am trying to write to a binary file , here is my snippet of code
#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;
}
}
我希望我的控制台输出是
I am expecting my console output to be
001 abc
002 def
相反,我得到了
002 def
002 def
谁能给我解释一下?
推荐答案
std::string 是一个类,它的对象不直接存储字符串的内容.
std::string is a class and the object of it doesn't store the content of the string directly.
它是为您的案例定义的实现,为简单起见,您可以这样理解:
It's implementation defined by for your case, for simplicity, you can understand it this way:
std::string 有一个存储指向实际数据的指针(比如 ptr)的成员.
std::string has a member that stores the pointer(say ptr) to the actual data.
和
std::string s = "001";
不会将ptr指向地址字符串001";它会分配内存并将字符串复制到该内存中.那么当你这样做时
would not point ptr to the address string of "001"; it would allocate memory and copy the string into that memory. Then when you do
s = "002";
它不需要重新分配内存来存储002";它只是将002"复制到之前存储001"的内存中.
it doesn't need to reallocate memory to store "002"; it just copy "002" to the memory that stores "001" previously.
这意味着,如果你转储字符串的原始数据,它不会改变.
This means, if you dump the raw data of the string, it does NOT change.
当你读回字符串原始数据时,它只会恢复指向002"的指针.
When you read back the string raw data, it would just restore the pointer that points to "002".
希望这会有所帮助.
相关文章