【发布时间】:2014-05-22 22:56:17
【问题描述】:
我正在尝试获取一个 BMP 文件并将其读入,然后对其中的像素执行操作以更改其颜色。我的问题是我无法将文件中的数据读入两个 BMP 标头结构。我能够很好地将所有数据读入第一个结构,但是在读入第二个结构时出现段错误。从代码中可以看出,第一个结构 FILEHEADER 被读取并包含它应该包含的所有正确数据,但第二个结构 BMPInfoHeader 没有被正确读取。为什么会出现这个段错误?
#include <stdio.h>
#include <stdlib.h>
typedef struct
{ unsigned short int Type; /* Magic identifier */
unsigned int Size; /* File size in bytes */
unsigned short int Reserved1, Reserved2;
unsigned int Offset; /* Offset to data (in B) */
} FILEHEADER; /* 14 Bytes */
typedef struct
{ unsigned int Size; /* Header size in bytes */
int Width, Height; /* Width / Height of image */
unsigned short int Planes; /* Number of colour planes */
unsigned short int Bits; /* Bits per pixel */
unsigned int Compression; /* Compression type */
unsigned int ImageSize; /* Image size in bytes */
int xResolution, yResolution;/* Pixels per meter */
unsigned int Colors; /* Number of colors */
unsigned int ImportantColors;/* Important colors */
} BMPInfoHeader; /* 40 Bytes */
typedef struct
{ unsigned char r; /* Red */
unsigned char b; /* Blue */
unsigned char g; /* Green */
} IMAGE;
int main(int argc, char *argv[]) {
FILE *BMPFile;
FILEHEADER BMPFileHeader;
BMPInfoHeader *InfoHeader;
BMPFile=fopen(argv[1],"rb");
unsigned char *BMPimage;
if (BMPFile==NULL) {
printf("\n\nERROR: File not opened properly\n\n");
return -1;
}
fread(&BMPFileHeader,sizeof(unsigned char),14,BMPFile);
fseek(BMPFile,BMPFileHeader.Offset,SEEK_SET);
fread(InfoHeader,sizeof(unsigned char),40,BMPFile);
if (BMPFileHeader.Type != 0x4D42) {
printf("\n\nERROR with fread\n\n");
return -1;
}
return 0;
}
【问题讨论】:
-
我搜索的时候没有看到这个问题,谢谢
标签: c segmentation-fault fread bmp