[英]Saving multiple structures into a binary file (C)
I'm writing down a function that should save 3 structures (2 of them are arrays of structs) in a binary file. 我正在编写一个函数,该函数应将3个结构(其中2个是结构数组)保存在一个二进制文件中。 Here's my function:
这是我的功能:
void saveFile(Struct1 *s1, Struct2 *s2, Struct3 s3) {
FILE *fp = NULL;
fp = fopen("save.bin", "w+b");
if (fp == NULL) {
printf("Save failed.\n");
}
fwrite(s1, sizeof(Struct1), struct3.nElements, fp);
fwrite(s2, sizeof(Struct2), NELEMENTS, fp);
fwrite(&s3, sizeof(Struct3), 1, fp);
printf("Save done.\n");
}
s1
have struct3.nElements
, s2
have NELEMENTS
(that's a constant) and s3
is just one struct and not an array. s1
具有struct3.nElements
, s2
具有NELEMENTS
(这是一个常数), s3
只是一个结构而不是数组。 When I try to open the save.bin with HexEditor it gives very different results from the ones I was expecting, I'm wondering if I used correctly the fwrite
function, especially for array of structs. 当我尝试使用HexEditor打开save.bin时,它给出的结果与我期望的结果截然不同,我想知道我是否正确使用了
fwrite
函数,尤其是结构数组。
There are small issues with you function that might cause problems: 您的功能存在一些小问题,可能会引起问题:
you define the function as taking s3
by value. 您将函数定义为按值取
s3
。 Why not pass a pointer to the third struct
? 为什么不将指针传递给第三个
struct
? Is the saveFile
function properly declared before the calling code? 在调用代码之前是否正确声明了
saveFile
函数? Are you sure the calling code passes the struct
by value? 您确定调用代码按值传递
struct
吗?
You forget to close the stream. 您忘记关闭流。 The handle gets lost, and the contents is not flushed to disk until the program exits.
句柄丢失,并且直到程序退出,内容才会刷新到磁盘。
You open the file in "w+b"
mode: write with read. 您以
"w+b"
模式打开文件:写入读取。 It is correct to use binary mode, but unnecessary to add the +
for read. 使用二进制模式是正确的,但是不必添加
+
进行读取。 Just use "wb"
. 只需使用
"wb"
。
If fopen
fails, you output a diagnostic message, but you do not return from the function. 如果
fopen
失败,则输出诊断消息,但不会从该函数返回。 You will invoke undefined behavior when trying to write to a NULL
stream pointer. 尝试写入
NULL
流指针时,将调用未定义的行为。
Regarding your question, the dump of the file does not correspond to what you expect... give us more information, such as the definitions of the different structures and the hex dump. 关于您的问题,文件的转储与您期望的不符...为我们提供了更多信息,例如不同结构的定义和十六进制转储。 Here are some ideas:
这里有一些想法:
0
: if the structures are in automatic storage or allocated with malloc
, their initial state is undefined and can change as a side effect of storing other fields. 0
:如果结构是自动存储的或使用malloc
分配的,则它们的初始状态是不确定的,并且可能由于存储其他字段的影响而改变。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.