查找文件中的特定字节

Finding a specific byte in a file

我有一个文件,我试图在其中查找以下字节序列: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 分音符 ÿ。

您的代码有两个问题。首先,请参阅:Why is “while ( !feof (file) )” always wrong?

第二个问题是getc (or fgetc) returns an int,不是char。就目前而言,0xFFchar 值在被提升为 if ((bytes == 0xFF))int 时被符号扩展(很可能是 0xFFFFFFFF)比较。因此,将 int 用于 bytes 变量并更改循环以测试为 EOF 信号读取的值:

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("%02X %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);
}