我有一個檔案,我試圖在其中查找以下位元組序列:0xFF、0xD8、0xFF 和 0xE0。現在,讓我們假設我只是在尋找 0xFF。我制作了這個程式進行測驗:
#include<stdio.h>
#include<stdlib.h>
#include<string.h>
void analyzeFile(char* filename)
{
FILE* filePtr = fopen(filename, "rb");
int numImages = 0;
while (!feof(filePtr))
{
char bytes;
bytes = getc(filePtr);
printf("%c", bytes);
if ((bytes == 0xFF))
{
numImages ;
printf("image found!\n");
}
}
printf("%d\n", numImages);
}
這不起作用。當我用引數“test.txt”呼叫analyzeFile時,它會很好地列印檔案的內容,但沒有檢測到單個0xFF位元組:
test.txt 的內容:
a????à1234
輸出:
a????à1234
0
作為參考,根據 ASCII,0xFF 相當于 y 分音符,?。
uj5u.com熱心網友回復:
您的代碼有兩個問題。首先,請參閱:為什么“while (!feof (file))”總是錯誤的?
第二個問題是getc(或fgetc)回傳一個int,而不是一個char。就目前而言,當您將 的char值提升為 an以進行比較時,它的值0xFF是符號擴展的(0xFFFFFFFF最有可能是 )。因此,使用您的變數并更改回圈以測驗為信號讀取的值:intif ((bytes == 0xFF))intbytesEOF
void analyzeFile(char* filename)
{
FILE* filePtr = fopen(filename, "rb");
if (!filePtr) { // Add some error handling...
printf("Could not open file!");
return;
}
int numImages = 0;
int bytes;
while ( ( bytes = getc(filePtr) ) != EOF) {
printf("X %c\n", (unsigned)bytes, bytes);
if (bytes == 0xFF) { // Removed redundant extra parentheses
numImages ;
printf("image found!\n");
}
}
fclose(filePtr); // Don't forget to close the file!
printf("%d\n", numImages);
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/364022.html
