debug read/write string to binary file(调试读/写字符串到二进制文件)
问题描述
我正在尝试写入二进制文件,这是我的代码片段
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".
希望这会有所帮助.
这篇关于调试读/写字符串到二进制文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:调试读/写字符串到二进制文件
基础教程推荐
- 这个宏可以转换成函数吗? 2022-01-01
- 常量变量在标题中不起作用 2021-01-01
- 如何通过C程序打开命令提示符Cmd 2022-12-09
- 在 C++ 中计算滚动/移动平均值 2021-01-01
- 静态库、静态链接动态库和动态链接动态库的 .lib 文件里面是什么? 2021-01-01
- 如何将 std::pair 的排序 std::list 转换为 std::map 2022-01-01
- 我有静态或动态 boost 库吗? 2021-01-01
- 如何在 C++ 中初始化静态常量成员? 2022-01-01
- 如何检查GTK+3.0中的小部件类型? 2022-11-30
- C++结构和函数声明。为什么它不能编译? 2022-11-07
