奇怪的行为写入/读取简单的二进制文件

问题描述

我正在一个二进制文件上读写。输出读取时出现小错误

字符串在那里,但有一些小片段,例如:(I"�U) (�U) 附加到大约 30% 的末尾

我在 Ubuntu 上使用 g++ 编译器

简化代码

struct Db_connection
{
    public:
        string name;
}

int Db_connection::write_config()
{
    ofstream config_f("config.dat",std::ios_base::binary | std::ios_base::out); //open file

    string str = name;
    int size = str.length();
    
    config_f.write(reinterpret_cast<char *>(&size),sizeof(int)); // write size of string in int size chunk
    config_f.write(str.c_str(),size); //write string

    config_f.close();
    return 0;
}

Db_connection read_config()
{
    ifstream config_f("config.dat",std::ios_base::binary | std::ios_base::in);

    Db_connection return_obj;
    int size;
    string data;

    config_f.read(reinterpret_cast<char *>(&size),sizeof(int)); // read string size
    char buffer[size];
    config_f.read(buffer,size); // read string
    data.assign(buffer);
    return_obj.name = data;

    return return_obj;
}

有什么明显的我在搞砸吗?这与Endian有关吗?我试图将代码最小化到绝对必要

实际代码更复杂。我有一个包含 2 个结构向量的类。 1 个结构体有四个字符串成员,另一个结构体有一个字符串和布尔值。这些函数实际上是该类的成员并(分别)返回该类。函数循环遍历向量,依次写入结构体成员。

两个奇怪的地方:

  1. 为了调试,我在读取和写入函数的每次迭代中都添加sizedata 变量的输出size 的结果是准确且一致的。 datawrite 侧是准确的,但在 read 侧有奇怪的特殊字符。我正在查看如下输出
Read Size: 12
Data: random addy2�U //the 12 human readable chars are there but with 2 extra symbols
  1. 最后的数据块(布尔值)每次都很好,所以我不认为存在文件指针问题。如果相关:每个 boolint 都可以。它只是字符串的一部分。

希望我犯了一个愚蠢的错误并且可以批评这个最小化的代码。实际例子太长了。

解决方法

非常感谢 WhozCraig,

以下编辑确实有效:


Db_connection read_config()
{
    ifstream config_f("config.dat",std::ios_base::binary | std::ios_base::in);

    Db_connection return_obj;
    int size;
    string data;

    config_f.read(reinterpret_cast<char *>(&size),sizeof(int)); // read string size
    vector<char> buff(size);
    config_f.read(buff.data(),size);
    data = string(buff.begin(),buff.end());
    return_obj.name = data;

    return return_obj;
}

正如 paddy 直接指出和 WhozCraig 所提到的,这段代码仍然需要实现一个标准化的、可移植的数据类型,以便将整数正确记录为二进制,并且还需要重新考虑写入函数。

非常感谢你们两位。在编写我的代码之前,我阅读了“cpp binary i/o”的 5-8 个顶级搜索结果,但仍然以这种混乱告终。你们救了我几个小时/几天的生命。