如何仅通过使用 C++ 提供文件路径来查找文件的幻数?

How to find the magic number of a file by just provding the path of the file using c++?

int main()
{

    FILE *fp = fopen("/root/ds/filehandling/a.pdf", "rb");
    unsigned char magic[4];
    fread((void *)magic, 1, 4, fp);
    cout << hex << "magic:";
    for (int i = 0;  i < 4;  i++)
        cout << " 0x" << int(magic[i]);
    cout << dec << endl;
    return 0;
}

这里的问题是我必须指定扩展名然后我才能得到幻数,但是我的 objective 是指定文件名而不给出它的扩展名以便在比较幻数时我可以确定它的类型。

这就是我想要的:

int main() {

    FILE *fp = fopen("/root/ds/filehandling/a", "rb");
    unsigned char magic[4];
    fread((void *)magic, 1, 4, fp);
    cout << hex << "magic:";
    for (int i = 0;  i < 4;  i++)
        cout << " 0x" << int(magic[i]);
    cout << dec << endl;
    return 0;
}

输出:魔法:0x25 0x50 0x44 0x46

但我得到 "SEGMENTATION FAULT"

您遇到了分段错误,因为没有 /root/ds/filehandling/a 这样的文件,因此 fopen 失败了,但您甚至从未检查过它的 return 值。 fp 将成为 nullptr,将其传递给 fread 之类的函数只是在自找麻烦。

这个问题确实与幻数无关;如果你想打开一个文件但不知道它的扩展名(即不知道它的全名),你将不得不 look in its directory 并通过模式匹配找到你想要的文件。请注意,可能不仅只有一个;例如如果有一个文件 a.txt 和一个文件 a.pdf,您将不得不决定选择哪个文件作为搜索词 "a"

记住,文件的 "extension" 只是其名称的最后一部分;这只是一个约定。很多文件连这个都没有!

对了,别忘了fclose