#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