繁体   English   中英

C++ 字节序会影响fstream的读写功能吗?

[英]C++ Is endianness affecting fstream's read and write functions?

我正在学习如何写入/读取二进制文件,并且我希望我的文件对于任何支持 C++ 17 的机器都是可读的。所以我有一个可怕的想法:如果 read() 和 write() 受到字节序的影响怎么办机器的?

例如:我在一台大端机器上运行这段代码,

#include <iostream>
#include <fstream>
#include <cstdint>

int main() {

    std::ofstream Output("Hey.txt", std::ofstream::out | std::ofstream::binary);

    if (Output.is_open()) {
        int16_t i = 42;
        Output.write((const char*)&i, 2);
    }

}

然后我把 Hey.txt 传给一个小端机器,然后在机器上运行这段代码,

#include <iostream>
#include <fstream>
#include <cstdint>

int main() {

std::ifstream Input("Hey.txt", std::ifstream::in | std::ifstream::binary);

    if (Input.is_open()) {
        int16_t i;
        Input.read((char*)&i, 2);
        std::cout << i << std::endl;
    }

}

程序会打印 42 吗? 还是 fstream 处理字节序差异? 如果没有,有没有办法防止字节序问题?

感谢您的关注。

两个简单的规则:

  1. 如果您要将二进制数据写入文件,请记录文件格式。

  2. 将二进制数据写入文件时,请确保写入的字节符合文件格式的要求。

如果文件格式显示有一个大端格式的 16 位 integer,并且您编写的代码可以读取或写入该文件,那么一切都会正常工作。

不要使用像这样(char*)&i这样的强制转换,因为这样字节将保存本机系统碰巧用于 16 位整数的任何格式,甚至不能保证(通过 C++ 标准)在运行同一系统上的相同代码。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM