在 C++ 中写入整数并从二进制文件中读回它们:字节数错误

Write integers and read them back from binary file in C++: number of bytes mismaych

我正在使用 fstream 将四个整数(a=1、b=2、c=3、d=4)写入一个二进制文件,但是当我尝试读回它们时,他们不匹配。

首先写入的二进制是4字节长。不应该是 16 个字节(4 个整数 x 4 bytes/int)吗?当我阅读时,如果我不对读取函数中的变量进行零初始化,我会得到奇怪的结果 1234 2 3 4,如果我这样做,我会得到 1234 0 0 0

另外,零初始化如何修改结果?我知道不初始化会导致糟糕的结果,但是 read() 中的变量究竟是如何获得与 write() 中的值匹配的值的?

#include <fstream>
#include <iostream>

void write()
{
    std::ofstream output( "test.bin", std::fstream::binary | std::fstream::out);
    int a=1, b=2, c=3, d=4;
    output << a << b << c << d;
    output.close();
}

void read()
{
    std::ifstream input( "test.bin", std::fstream::binary | std::fstream::in);
    int a, b, c, d;
    // int a=0, b=0, c=0, d=0;
    input >> a >> b >> c >> d;
    input.close();

    std::cout << a << " " << b << " " << c << " " << d << " " << std::endl;
}

int main()
{
    write();
    read(); // Shows 1234 2 3 4 or 1234 0 0 0
}
output << a << b << c << d;

正在使用 operator<< 流插入运算符,用于 格式化的 输出。所有四个整数都被格式化为字符串,并且输出之间没有分隔符。

你可以通过实际查看你自己的文件来简单地看到这一点(如果你希望文件包含不可打印的二进制值,请使用 hexdump 或类似的)。它包含字符串 1234,不是吗?

您想要 未格式化 输出,这意味着您不希望流将整数格式化为字符串。这是通过调用 write instead (and read 而不是 operator>>).

来完成的

输出:

output.write(reinterpret_cast<char *>(&a), sizeof(a));
output.write(reinterpret_cast<char *>(&b), sizeof(b));
// etc.

输入:

input.read(reinterpret_cast<char *>(&a), sizeof(a));

您可能希望 std::fstream::binary 开放模式阻止流插入将整数格式化为字符串,但这是不正确的:binary mode 仅控制换行行为。 <<>> 运算符始终用于格式化 I/O.