调试读/写字符串到二进制文件

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

希望这会有所帮助.

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

本站部分内容来源互联网,如果有图片或者内容侵犯您的权益请联系我们删除!

相关文档推荐

Rising edge interrupt triggering multiple times on STM32 Nucleo(在STM32 Nucleo上多次触发上升沿中断)
How to use va_list correctly in a sequence of wrapper functions calls?(如何在一系列包装函数调用中正确使用 va_list?)
OpenGL Perspective Projection Clipping Polygon with Vertex Outside Frustum = Wrong texture mapping?(OpenGL透视投影裁剪多边形,顶点在视锥外=错误的纹理映射?)
How does one properly deserialize a byte array back into an object in C++?(如何正确地将字节数组反序列化回 C++ 中的对象?)
What free tiniest flash file system could you advice for embedded system?(您可以为嵌入式系统推荐什么免费的最小闪存文件系统?)
Volatile member variables vs. volatile object?(易失性成员变量与易失性对象?)