【问题标题】:Finding a specific byte in a file在文件中查找特定字节
【发布时间】:2022-01-02 01:51:50
【问题描述】:

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

作为参考,0xFF 相当于 y-diaeresis,ÿ,根据 ASCII。

【问题讨论】:

  • 0xFF 不是由 ASCII 定义的。使用hexdump 或其他一些十六进制查看器以数字形式查看实际字节
  • 还将您的类型更改为 unsigned char,否则您的比较将不起作用(请参阅这个有趣的实验:ideone.com/Pk0rGg)。这是因为在比较和整数提升期间,带符号的 char 值将“符号扩展”到 0xFFFFFFFF 并与 0x000000FF 进行比较
  • while (!feof(filePtr)) 是一个错误。 feof 返回早期读取是否找到 EOF。只需调用getc 并检查它是否返回EOF
  • @humanbean 很可能它正在检测EOF。按照上面的建议更改为int。并摆脱while (!feof(filePtr)) - 请参阅Why is “while ( !feof (file) )” always wrong?
  • @humanbean 表示你的文件不包含 0xFF 字节。

标签: c file char


【解决方案1】:

您的代码存在两个问题。第一种见:Why is “while ( !feof (file) )” always wrong?

第二个问题是getc (or fgetc) returns an int,而不是char。就目前而言,当您的char0xFF 被提升为int 以进行if ((bytes == 0xFF)) 比较时,它被符号扩展(很可能是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);
}

【讨论】:

  • 与问题无关,但将(char)bytes 作为printf 的参数不是没用吗?默认促销活动会将其转换回int
  • 感谢您的帮助!
  • (char)bytes 的值是在bytes &gt; CHAR_MAX 的情况下定义的实现(只有当char 是有符号类型时才会发生),所以最好不要将其转换为char。此外,%X 需要 unsigned int,因此您确实需要一个演员表(到 unsigned int)。
  • @IanAbbott Fair 评论 - 见编辑。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-08-08
  • 1970-01-01
相关资源
最近更新 更多