如何使用fwrite来写一个结构到一个文件? [英] How to write a struct to a file using fwrite?
问题描述
我很新的C,和我有fwrite的麻烦。
I'm very new to C, and I am having trouble with fwrite.
我期待使用拥有两个值的结构:
I'm looking to use a struct that holds two values:
struct keyEncode{
unsigned short key[2];
unsigned short encoded[2];
};
然后我宣布我的结构,并在我的主要指向一个结构:
I then declare my struct and a pointer to that struct in my main:
struct keyEncode keynEncode;
struct keyEncode *storedVal = &keynEncode;
我然后分配值的结构和想用的fwrite的结构写入一个文件:
I then assign values to the struct and want to write the struct to a file using fwrite:
keynEncode.key[0] = k1[0];
keynEncode.key[1] = k1[1];
keynEncode.encoded[0] = p[0];
keynEncode.encoded[1] = p[1];
// i tried to use storedVal.key[0] = k1[0]; but i was getting compile errors
fwrite(storedVal, sizeof(storedVal), 0xffff, fp);
现在我的问题是什么的fwrite写入到文件中。
Now my problem is that fwrite writes nothing to the file.
我在哪里去了?
推荐答案
您正在使用的sizeof
上的指针,这将不计算有效结构的大小,但指针中的一个(即可以是4或8个字节)。与的sizeof尝试(结构KEYEN code)
(的sizeof(KEYEN code)
是不够的,如果你使用C ++)。
You are using sizeof
on a pointer, this won't calculate the size of the effective struct but the one of the pointer (that could be 4 or 8 bytes). Try with sizeof(struct keyEncode)
(sizeof(keyEncode)
is enough if you are using C++).
然后,我不知道为什么你有 0xFFFF的
的数量,应该不是只是 1
?
Then I don't get why you have 0xFFFF
as count, shouldn't it be just 1
?
这篇关于如何使用fwrite来写一个结构到一个文件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!