#include <stdio.h>
#include <stdint.h>
#include <stdlib.h>
int main()
{
FILE* bmp = NULL;
uint32_t offset;
uint8_t* temp = NULL;
size_t read;
unsigned int x_dim = 600, y_dim = 388;
bmp = fopen("test_colour.bmp", "r");
if (!bmp)
return -1;
/* Get the image data offset */
fseek(bmp, 10, SEEK_SET);
fgets((char*)&offset, 4, bmp);
printf("Offset = %u\n", offset);
temp = malloc(3*x_dim*y_dim*sizeof(uint8_t));
if (!temp)
return -1;
/* Go the the position where the image data is stored */
fseek(bmp, offset, SEEK_SET);
/* Copy image data to array */
printf("%u bytes requested!\n", 3*x_dim*y_dim);
read = fread((void*)temp, sizeof(uint8_t), 3*x_dim*y_dim, bmp);
printf("%Iu bytes read!\n", read);
fclose(bmp);
free(temp);
return 0;
}
我正在使用上面的代码来读取一个24位像素BMP图像的RGB数据到一个数组。根据BMP规范,在偏移量10处给出从图像数据开始处(在BMP标题之后)开始的文件的偏移量。执行上述代码时,我会得到以下输出。fread意外的返回值()
Offset = 54
698400 bytes requested!
33018 bytes read!
由于文件大小为698454字节(= 698400 + 54),偏移量输出似乎是正确的。但是,fread()
返回的值似乎表示不能读取整个图像数据。但是,随后我使用temp
阵列中的数据将RGB数据转换为灰度并将此数据再次写入BMP文件。目测检查输出图像并不表示任何错误,即似乎我实际上首先读取了整个输入图像,尽管fread()
似乎表示不同。
有人可以解释这种行为吗?
有两个问题:1)你可以在调用'fread'之后检查'temp'的内容,看它是否在33018字节后实际停止读取? 2)我不熟悉'%Iu'格式说明符 - 你能在调试器中检查'read'的实际值吗? – Treb 2012-07-30 07:52:54
我不认为这是什么导致你看到的症状,但你应该使用正确的'printf'格式字符串。 'size_t'的格式是'“%zu”'。 '“%Iu”'是非标准的。如果你的实现不支持'“%zu”',你可以使用'printf(“%lu read read!\ n”,(unsigned long)read);' – 2012-07-30 07:55:23
我使用gcc和MinGW进行编译,编译器无法识别'%zu'说明符(我曾尝试使用该说明符)。我读过,必须在窗口中使用'%Iu'。 – simon 2012-07-30 08:04:47