在C++中,如何读取嵌入在可执行文件中的文件?

bkkx9g8r  于 2022-11-19  发布在  其他
关注(0)|答案(1)|浏览(196)

我有一张名为photo.jpg的照片。我使用xxd -i为我的图像文件生成了一个C++文件。输出如下所示:

unsigned char photo_jpg[] = {

    0xff, 0xd8, 0xff, 0xe0, 0x00, 0x10, 0x4a, 0x46, 0x49, 0x46, 0x00, 0x01,

    0x01, 0x01, 0x00, 0x48, 0x00, 0x48, 0x00, 0x00, 0xff, 0xdb, 0x00, 0x84,...};

unsigned int photo_jpg_len = 24821;

我将该文件嵌入到我的main.cpp文件中,并构建它以生成我的可执行文件。
我怎么可能从可执行文件中读取十六进制转储文件中的图像文件呢?
"我尝试过什么"
我使用了xxd myfile.exe > file.txt.
当我检查用xxd生成的可执行文件的十六进制转储时,我发现photo_jpg字符数组的字节在可执行文件的某个地方。It is a screenshot of my executable hex dump.
我如何读取它并将其存储在字符数组中,就像它在嵌入到可执行文件中之前一样?

wgeznvg7

wgeznvg71#

首先,我把我的zip文件转换成一个字符串,这是与这个命令:
xxd -p archive.zip > myfile.txt
然后,我使用这段代码在C++中生成zip文件十六进制转储的多行字符串:

#include <fstream>
#include <string>
int main()
{
    std::ifstream input("file.txt");
    std::ofstream output("string.txt");
    std::string double_coute = "\"";
    std::string line;
    while (getline(input, line))
    {
        std::string to_be_used = double_coute + line + double_coute + "\n" ;
        output << to_be_used;
    }
    output.close();
    input.close();
    return 0;
}

然后,我把string.txt的内容放在一个全局变量中,使用下面的函数,我可以编写一个生成zip文件的程序。

void WriteHexDatatoFile(std::string &hex)
{
    std::basic_string<uint8_t> bytes;

    // Iterate over every pair of hex values in the input string (e.g. "18", "0f", ...)
    for (size_t i = 0; i < hex.length(); i += 2)
    {
        uint16_t byte;

        // Get current pair and store in nextbyte
        std::string nextbyte = hex.substr(i, 2);

        // Put the pair into an istringstream and stream it through std::hex for
        // conversion into an integer value.
        // This will calculate the byte value of your string-represented hex value.
        std::istringstream(nextbyte) >> std::hex >> byte;

        // As the stream above does not work with uint8 directly,
        // we have to cast it now.
        // As every pair can have a maximum value of "ff",
        // which is "11111111" (8 bits), we will not lose any information during this cast.
        // This line adds the current byte value to our final byte "array".
        bytes.push_back(static_cast<uint8_t>(byte));
    }

    // we are now generating a string obj from our bytes-"array"
    // this string object contains the non-human-readable binary byte values
    // therefore, simply reading it would yield a String like ".0n..:j..}p...?*8...3..x"
    // however, this is very useful to output it directly into a binary file like shown below
    std::string result(begin(bytes), end(bytes));
    std::ofstream output_file("khafan.zip", std::ios::binary | std::ios::out);
    if (output_file.is_open())
    {
        output_file << result;
        output_file.close();
    }
    else
    {
        std::cout << "Error could not create file." << std::endl;
    }
}

"但这有什么意义"
重点是你可以在你的zip文件中有任何类型的资源。这样,你就可以用你的程序生成所需的资源,并用它们做一些事情。我认为这很酷。

相关问题