簡體   English   中英

識別文件是否為 gzip 文件

[英]Identify if a file is a gzip file


如果打開的文件是 gzip 文件,我需要使用 C++ 檢查。
在 Python 中,我使用以下代碼來識別文件是否被壓縮:
 test_file = "junk.txt.gz" with open(test_file, "rb") as f: f_read_first_two_bytes = f.read(2) if f_read_first_two_bytes==b'\x1f\x8b': print("The file is a gzipped file", end='\n')

C++ 中的等價物是什么?

我是 C++ 的新手並嘗試了以下方法,但這顯然不是正確的方法。

 int main() { char p[3] = {0}; p[2] = '\n'; // open the junk.txt.gz file. We do not want to just go by the '.gz' in the file name. // but want to check just like the way we did in the Python code. ifstream is("./junk.txt.gz", std::ios::in|std::ios::out|std::ios::binary); //read two characters into p is.read(p,2); cout << std::hex << p[0] << " " << std::hex << p[1] << endl; return 0; }

但這顯然不是正確的方法。

顯然不是,因為您不會將字節與任何內容進行比較。 否則,它幾乎與 Python 程序一樣“正確”。

進行比較的一種簡單方法是將字節解釋為unsigned char

auto up = reinterpret_cast<unsigned char*>(p);
if (up[0] == 0x1f && up[1] == 0x8b)

PS 這不一定是對 gzip 文件最准確的測試。 它可能有誤報。

我建議不要嘗試手動實施測試。 有用於此目的的開源庫(就像大多數目的一樣)。

您可以安裝libmagic庫,而不是自己實施指紋檢查,該庫包含許多針對不同文件類型的指紋。

Ubuntu: apt install libmagic-dev ,Fedora: dnf install file-devel - 或從https://github.com/file/file下載源代碼

檢查您在命令行中提供的文件的示例程序:

#include <magic.h>

#include <filesystem>
#include <iostream>
#include <memory>
#include <stdexcept>
#include <string>

// A small class to manage the libmagic "cookie"
class MagicCookie {
public:
    // MAGIC_MIME - Return a MIME type string, instead of a textual description.
    MagicCookie() : cookie(magic_open(MAGIC_MIME), &magic_close) {
        if(not cookie)
            throw std::runtime_error("unable to initialize magic library");

        if(magic_load(cookie.get(), nullptr)) {
            throw std::runtime_error(std::string("cannot load magic database: ") +
                                     magic_error(cookie.get()));
        }
    }

    // A function that checks a file and returns its MIME type
    const char* File(const std::filesystem::path& file) {
        return magic_file(cookie.get(), file.string().c_str());
    }

private:
    std::unique_ptr<std::remove_pointer_t<magic_t>, decltype(&magic_close)> cookie;
};

int main(int argc, char* argv[]) {
    MagicCookie mc;

    // Find the MIME type for all files given on the command line:
    for(int idx = 1; idx < argc; ++idx) {
        std::cout << argv[idx] << ": MIME: " << mc.File(argv[idx]) << '\n';
    }
}

一個gzip ed 文件將顯示其 MIME 類型application/gzip; charset=binary application/gzip; charset=binary所以你可以很容易地與之比較:

some_file.gz: MIME: application/gzip; charset=binary

如果MIME不是您想要的,則可以在此處找到其他打開模式: https://man7.org/linux/man-pages/man3/libmagic.3.html 如果需要,它甚至可以分析壓縮文件的內容。

編譯:

-std=c++17 -lmagic

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM