是否可以在不同系统中使用fwrite转储文件?

mon*_*ing 0 c++ binary struct fwrite fread

我可以假设使用fwrite生成的文件和使用fread读取的文件可以跨不同系统移植.32位/ 64位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);
Run Code Online (Sandbox Code Playgroud)

结构怎么样?

struct mat_t{
    size_t x;
    size_t y;
    double **matrix;
}
Run Code Online (Sandbox Code Playgroud)

这些便携式吗?

Mar*_*ork 5

简答:没有

答案很长:

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

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

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.
Run Code Online (Sandbox Code Playgroud)

您有两个主要选择:

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