写作“打包”;使用 C 构造文件
如何使用 C 将结构“打包”和“写入”到文件中,以便:
struct a { uint64_t a; char* b; uint16_t c; } a; a b; b.a = 3; b.b = "Hello"; b.c = 4;
写入文件
00 00 00 00 00 00 00 03 48 65 6c 6c 6f 00 00 04
How can I "pack" and "write" a struct to a file using C so that:
struct a { uint64_t a; char* b; uint16_t c; } a; a b; b.a = 3; b.b = "Hello"; b.c = 4;
gets written to the file as
00 00 00 00 00 00 00 03 48 65 6c 6c 6f 00 00 04
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
在 C 中,您必须编写一个函数来为您完成此操作。您不能只是将结构复制到磁盘,因为
b
是一个没有支持字符串就没有任何意义的指针。而且,除非您知道(并且可以控制)编译器如何打包其结构,否则即使没有指针,您最好还是使用实用函数。而且,好像这还不够,您还应该输出字符串的长度,以便您知道要读回多少字节。
你会寻找类似的东西:
In C, you'll have to code a function to do this for you. You can't just blat the structure out to disk because
b
is a pointer that makes no sense without the backing string. And, unless you know (and can control) how your compiler packs its structures, you're better off with a utility function anyway, even without pointers.And, as if that wasn't enough, you should output the length of the string as well so you know how many bytes to read back.
You'll be looking for something like:
您必须编写自己的方式来序列化这些数据;编译器不会为您提供处理字符串的内置方法。那里有序列化库,但我不知道任何直接 C 语言的库。
但是,请考虑使用更结构化的方法来序列化数据,例如 json 或 xml。即使是 INI 文件也比原始二进制转储更好。这样做的原因是:
you must write your own way to serialize this data; the compiler won't hand you a built-in way to deal with the string. There are serialization libraries out there but I don't know any for straight C.
But, consider using a more structured method for serializing data, such as json or xml. Even an INI file is better than raw binary dump. Reasons for this are:
以下内容会有帮助吗?
用法:
Will the following help?
Usage:
如果您不在结构中使用指针并且显式定义打包对齐方式,则可以安全地将结构打包到字节数组中。
例如(海湾合作委员会):
You can safely pack your structure into byte array, if you will not use pointers in it and will explicitly define packing alignment.
For example (gcc):