[英]reading a bmp header in C
I wrote a program to read a BMP file header. 我编写了一个程序来读取BMP文件头。 The code is the following:
代码如下:
#include <stdio.h>
typedef unsigned short WORD;
typedef unsigned short BYTE;
typedef unsigned int DWORD;
typedef struct _WinBMPFileHeader {
WORD FileType;
DWORD FileSize;
WORD Reserved1;
WORD Reserved2;
DWORD BitmapOffset;
} WINBMPFILEHEADER;
int main(int argc, char* argv[]) {
WINBMPFILEHEADER *header = NULL;
FILE *fptr;
size_t bytes_read;
if (argc == 2) {
fptr = fopen(argv[1], "r");
bytes_read = fread(header, sizeof(WINBMPFILEHEADER), 1, fptr);
}
else
printf("The number of parameters is wrong.\n");
return 0;
}
When I run the program I have a segmentation fault because of fread. 当我运行程序时,由于读取错误,出现了段错误。 What is the reason of this fault?
此故障的原因是什么?
Look at this 看这个
WINBMPFILEHEADER *header = NULL;
...
bytes_read = fread(header, sizeof(WINBMPFILEHEADER), 1, fptr);
The segmentation fault is because you are passing NULL
to the function. 分段错误是因为您将
NULL
传递给函数。 You must allocate memory for header
, perhaps 您必须为
header
分配内存
header = malloc (sizeof(WINBMPFILEHEADER));
Also you have a declaration error as a separate issue: 另外,您还有一个声明错误作为单独的问题:
typedef unsigned short BYTE;
should be 应该
typedef unsigned char BYTE;
Finally you must make sure you don't have endian issues with any 2 or 4 (I don't think there are any 8) byte fields, a bit off-topic. 最后,您必须确保任何2或4(我认为没有8)字节字段都没有字节序问题,这有点题外话了。
try this one, its a sipmle one i use 试试这个,我用的一个
synHead reader(FILE* img) {
synHead info;
fseek(img, 10, 0);
fread(&info.D, 1, 4, img);
fseek(img, 18, 0);
fread(&info.W, 1, 4, img);
fseek(img, 22, 0);
fread(&info.H, 1, 4, img);
return(info);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.