什么是writie一个struct在C文件中的可移植的方法? [英] What is a portable way to writie a struct to a file in C?

查看:148
本文介绍了什么是writie一个struct在C文件中的可移植的方法?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要一个C 结构序列化到一个可移植的方式的文件,这样我可以阅读在其他机器上的文件,并可以保证,我会得到那我把同样的事情。

I need to serialize a C struct to a file in a portable way, so that I can read the file on other machines and can be guaranteed that I will get the same thing that I put in.

该文件格式不只要事情,因为它是紧凑合理(写出一个结构的内存重新presentation将是理想的,如果它不是为便携性的问题。)

The file format doesn't matter as long as it is reasonably compact (writing out the in-memory representation of a struct would be ideal if it wasn't for the portability issues.)

有没有干净的方式很容易地做到这一点?

Is there a clean way to easily achieve this?

推荐答案

您基本上是设计一个二进制网络协议,因此您可能希望使用现有的库(如谷歌的协议缓冲区)。如果你仍然想设计你自己的,你可以这样做实现书写原料结构合理的便携性:

You are essentially designing a binary network protocol, so you may want to use an existing library (like Google's protocol buffers). If you still want to design your own, you can achieve reasonable portability of writing raw structs by doing this:


  1. 收拾好你的结构(GCC的 __属性__((包装)),MSVC的的#pragma包)。这是编译器特定的。

  2. 确保您的整数字节顺序是正确的( htons htonl )。这是架构特定的。

  3. 请不要使用指针的字符串(使用的字符缓冲区)。

  4. 使用C99确切的整数大小( uint32_t的等)。

  5. 确保code只编译其中 CHAR_BIT 8,这是最常见的,或者以其他方式处理字符串转换为8位流字节。有一些环境,其中 CHAR_BIT != 8,但他们往往是专用硬件。

  1. Pack your structs (GCC's __attribute__((packed)), MSVC's #pragma pack). This is compiler-specific.
  2. Make sure your integer endianness is correct (htons, htonl). This is architecture-specific.
  3. Do not use pointers for strings (use character buffers).
  4. Use C99 exact integer sizes (uint32_t etc).
  5. Ensure that the code only compiles where CHAR_BIT is 8, which is the most common, or otherwise handles transformation of character strings to a stream of 8-bit octets. There are some environments where CHAR_BIT != 8, but they tend to be special-purpose hardware.

有了这个,你可以确信你使用的是相同的结构定义,你会得到另一端相同的结果一样长。我不知道浮点数重新presentation,但是,但是我通常会避免发送这些。

With this you can be reasonably sure you will get the same result on the other end as long as you are using the same struct definition. I am not sure about floating point numbers representation, however, but I usually avoid sending those.

您可能要解决无关便携的另一件事是向后通过引入长度第一场的相容性,和/或使用版本标记。

Another thing unrelated to portability you may want to address is backwards compatibility by introducing length as a first field, and/or using version tag.

这篇关于什么是writie一个struct在C文件中的可移植的方法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆