c++ - 使用 fwrite 转储的文件是否可以跨不同系统移植?

标签 c++ binary struct fread fwrite

我是否可以假设使用 fwrite 生成并使用 fread 读取的文件可以跨不同系统移植。 32bit/64bit windows,osx,linux.

//dumping
FILE *of =fopen("dumped.bin","w");
double *var=new double[10];
fwrite(var, sizeof(double), 10,FILE);
//reading
file *fo=fopen()
double *var=new double[10];
fread(var,sizeof(double),10,of);

那么结构呢

struct mat_t{
    size_t x;
    size_t y;
    double **matrix;
}

这些是可移植的吗?

最佳答案

简短回答:

长答案:

你正在写出数据的二进制表示。
这不能跨平台或操作系统甚至编译器移植。

你写的所有对象都有可以改变的东西:

int:        size and endianess.
double:     size and representation.
structure:  Each member has to be looked at individually.
            The structure itself may be padded different on different compilers.
            Or even the same compiler with different flags.
pointers:   Are meaningless even across processes on the same machine.
            All pointers have to be converted into something meaningful like
            a named object that is provided separately. The transport will then
            have to convert named objects into pointers at the transport layer
            at the destination.

您有两个主要选择:

  • 流式传输数据。
    这基本上是将结构转换为文本表示并发送字符串。对于小对象,API 结构是当前进行跨平台/语言通信的标准方法(尽管数据通常以某种格式包装,如 XML 或 Json)。
  • 转换为网络中立的二进制格式
    为此,我们有 htonl() 和 family of functions() 用于转换整数。 double 更难,通常转换为两个整数(值取决于精度要求)。字符串被转换为一个长度后跟一个字符序列等。然后每个字符串都被单独写入流中。这可以比流式传输更紧凑(因此更高效)。不利的一面是,您将两端紧密耦合到一种非常特定的格式,从而使解决方案特别脆弱,并且在错误情况下更难纠正。

关于c++ - 使用 fwrite 转储的文件是否可以跨不同系统移植?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2193472/

相关文章:

c++ - 如何将字节形式的输入写入输出文件?

c++ - 二维 vector 的运行时错误

windows - Perl 5.12 使用为 Perl 5.6 创建的 DLL 加载模块

java - 字节组合生成器和定序器

audio - 提取音频文件的二进制表示

c - 将指针传递给结构数组

C 列表 - 访问结构体的成员并打印它

c++ - 使用模板

c++ - 指定容器类型的迭代器类型的部分特化

C99 指向结构的指针,该结构包含指向结构的指针