调试读/写字符串二进制文件 [英] debug read/write string to binary file

查看:110
本文介绍了调试读/写字符串二进制文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图写一个二进制文件,这里是我的code的片段

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

能向我解释的人?

Can someone explain to me?

推荐答案

的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 ::串具有这样的指针(例如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到pviously存储001$ P $内存。

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".

希望这有助于。

这篇关于调试读/写字符串二进制文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆