[英]In C++, how do you read a file that is embedded in an executable?
我有一張名為 photo.jpg 的照片。 我使用xxd -i
為我的圖像文件生成一個 C++ 文件。 而 output 是這樣的:
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 字符數組的字節位於可執行文件中的某處。 您可以在下圖中看到:這是我的可執行十六進制轉儲的屏幕截圖。
我如何讀取它並將其存儲在字符數組中,就像嵌入到我的可執行文件之前一樣?
起初,我將我的 zip 文件轉換為一個字符串,它是用這個命令:
xxd -p archive.zip > myfile.txt
然后我使用這段代碼在我的 zip 文件的十六進制轉儲的 C++ 中生成一個多行字符串:
#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 的內容放入一個全局變量中。 使用下面的 function 我能夠編寫一個生成 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 文件中可以包含任何類型的資源。 通過這種方式,您可以用您的程序生成所需的資源並用它們做一些事情。 我認為這很酷。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.