我有一个文件,并且使用 CI 想要使用 fread() (来自 stdio.h)读取它的内容并将其写入结构的成员中。(在我的情况下,开头有一个 2 字节的 int,后跟一个 4 字节的 int。)但是在将文件的内容正确写入结构的前两个字节变量后,它会跳过两个字节,然后继续执行后四个字节变量。
为了演示,我创建了一个 16 字节的文件来读取。在十六进制中它看起来像这样(小端):
22 11 66 55 44 33 11 11 00 00 00 00 00 00 00 00
使用以下代码,我希望第一个变量 ,twobytes
是0x1122
,第二个变量 ,fourbytes
是0x33445566
。但相反,它打印:
twobytes: 0x1122
fourbytes: 0x11113344
sizeof(FOO) = 8
&foo : 0061FF14
&foo.two : 0061FF14
&foo.four: 0061FF18
跳过字节 3 和 4 ( 0x66
& 0x55
)。代码:
#include <stdio.h>
#include <stdint.h>
int main(void) {
FILE* file = fopen("216543110.txt", "r");
if (file==NULL) { return 1; }
typedef struct
{
uint16_t twobytes;
uint32_t fourbytes;
}__attribute__((__packed__)) // removing this attribute or just the underscores around packed does not change the outcome
FOO;
FOO foo;
fread(&foo, sizeof(FOO), 1, file);
printf("twobytes: 0x%x \n", foo.twobytes);
printf("fourbytes: 0x%x \n\n", foo.fourbytes);
printf("sizeof(FOO) = %d\n", sizeof(FOO));
printf("&foo : %p\n", &foo);
printf("&foo.two : %p\n", &foo.twobytes);
printf("&foo.four: %p\n", &foo.fourbytes);
fclose(file);
return 0;
}
使用具有两个相同大小整数的结构按预期工作。
所以:使用 fread() 写入不同大小的变量会导致跳过字节:
22 11
.. ..
44 33 11 11
...
代替
22 11
66 55 44 33
...
我知道关于字节对齐的一些东西在这里发挥了作用,但这对字节的读取有何影响?如果 C 想要为结构添加填充,这对从文件中读取有何影响?我不在乎 C 是否将结构成员存储为
or
,我很困惑为什么它无法正确读取我的文件。22 11
.. ..
66 55 44 33
...
22 11
66 55 44 33
...
另外,我正在使用gcc version 6.3.0 (MinGW.org GCC-6.3.0-1)