How to get magic number of a binary file

前端 未结 6 1701
傲寒
傲寒 2020-12-06 06:13

There is a magic number associated with each binary file , does anyone know how to retrieve this information from the file?

6条回答
  •  悲哀的现实
    2020-12-06 07:08

    Expounding on @nos's answer:

    Example below uses the default magic database to query the file passed on the command line. (Essentially an implementation of the file command. See man libmagic for more details/functions.

    #include 
    #include 
    #include 
    int main(int argc, char **argv) {
        if (argc == 1) {
                std::cerr << "Usage "  << argv[0] << " [filename]" << std::endl;
                return -1;
        }
        const char * fname = argv[1];
        magic_t cookie = magic_open(0);
        assert (cookie !=nullptr);
        int rc = magic_load(cookie, nullptr);
        assert(rc == 0);
        auto f=  magic_file(cookie, fname);
        if (f ==nullptr) {
            std::cerr << magic_error(cookie) << std::endl;
        } else {
            std::cout << fname << ' ' << f << std::endl;
        }
    
    }
    

提交回复
热议问题