[英]Why doesn't fread() into my struct work?
I have the following code that reads from a file into a struct and into an arrary. 我有以下代码,这些代码从文件读取到结构和库中。 When I try to print the data in the struct it isn't what I would expect.
当我尝试在结构中打印数据时,这不是我期望的。 The array prints what would be expected, the first two characters in the file.
该数组将打印出预期的结果,即文件中的前两个字符。
typedef struct __attribute__((packed)){
uint8_t magic[2]; /* the magic number used to identify the BMP file:
0x42 0x4D (Hex code points for B and M).
The following entries are possible:
BM - Windows 3.1x, 95, NT, ... etc
BA - OS/2 Bitmap Array
CI - OS/2 Color Icon
CP - OS/2 Color Pointer
IC - OS/2 Icon
PT - OS/2 Pointer. */
} bmp_header_t;
bool
bmp_get_header_from_file(FILE *fp, bmpfile_t *bmp)
{
fseek(fp, 0L, SEEK_SET);
char magic[1];
fread(magic, 1, 2, fp);
printf("magic is: %c, %c\n", magic[0], magic[1]);
fread(&bmp->header, 1, 2, fp);
printf("magic is: %c, %c\n", bmp->header.magic[0], bmp->header.magic[1]);
}
When you do the first fread
, you advance the read position of the file, so the second fread
will read the next two bytes. 当你做的第一
fread
,你预先将文件的读取位置,所以第二fread
将读取接下来的两个字节。 You'll need to add another fseek
before the second read. 您需要在第二次阅读之前添加另一个
fseek
。
First things first, char magic[1]
gives you one byte, not two. 首先,
char magic[1]
给您一个字节,而不是两个字节。 Reading two bytes into that is a definite no-no. 读两个字节绝对是不行。
Second, the subsequent fread
will attempt to read the next two bytes in the file rather than the first two, because the first fread
has advanced the file pointer. 其次,在随后
fread
将试图读取该文件,而不是前两个在接下来的两个字节,因为第一fread
拥有先进的文件指针。
Something like this would be better: 这样的事情会更好:
char magic[2];
fseek(fp, 0L, SEEK_SET);
fread(magic, 1, 2, fp);
printf("magic is: %c, %c\n", magic[0], magic[1]);
fseek(fp, 0L, SEEK_SET);
fread(&bmp->header, 1, 2, fp);
printf("magic is: %c, %c\n", bmp->header.magic[0], bmp->header.magic[1]);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.