实现将任意文件内容转换为C++字节数组,并生成对应的头文件。
功能说明:实现将任意文件内容转换为C++字节数组,并生成对应的头文件。
生成的数组可以嵌入到程序中,运行时将数组内容写入临时文件供使用,使用后自动删除临时文件。
改进建议:可以增加对大型文件的分块处理支持,避免内存占用过高。
#pragma once
#include <vector>
#include <string>
#include <fstream>
#include <iostream>
#include <cstdlib>
#include <cstdint>
#pragma comment(lib,"winmm.lib")
class FileToByteArrayConverter {
private:
std::vector<uint8_t> byteArray;
std::string tempFilePath;
public:
// 将文件内容转换为字节数组
bool convertFileToByteArray(const std::string& inputFilePath) {
std::ifstream inputFile(inputFilePath, std::ios::binary);
if (!inputFile.is_open()) {
std::cerr << "Error: Cannot open input file: " << inputFilePath << std::endl;
return false;
}
// 获取文件大小
inputFile.seekg(0, std::ios::end);
size_t fileSize = (size_t)inputFile.tellg();
inputFile.seekg(0, std::ios::beg);
// 读取文件内容到字节数组
byteArray.resize(fileSize);
inputFile.read(reinterpret_cast<char*>(byteArray.data()), fileSize);
inputFile.close();
return true;
}
// 生成头文件
bool generateHeaderFile(const std::string& outputHeaderPath,const std::string& arrayName) {
std::ofstream headerFile(outputHeaderPath);
if (!headerFile.is_open()) {
std::cerr << "Error: Cannot create header file: " << outputHeaderPath << std::endl;
return false;
}
// 写入头文件保护
headerFile << "#ifndef " << arrayName << "_H" << std::endl;
headerFile << "#define " << arrayName << "_H" << std::endl << std::endl;
// 写入数组声明
headerFile << "#include <cstdint>" << std::endl << std::endl;
headerFile << "const uint8_t " << arrayName << "[] = {" << std::endl;
// 写入字节数组内容
for (size_t i = 0; i < byteArray.size(); ++i) {
headerFile << "0x" << std::hex << static_cast<int>(byteArray[i]);
if (i < byteArray.size() - 1) {
headerFile << ", ";
}
if ((i + 1) % 16 == 0) {
headerFile << std::endl;
}
}
headerFile << "};" << std::endl;
headerFile << "const size_t " << arrayName << "_size = " << std::dec << byteArray.size() << ";" << std::endl;
headerFile << std::endl << "#endif" << std::endl;
headerFile.close();
return true;
}
// 将字节数组写入临时文件
bool writeToTempFile() {
// 生成临时文件名
//tempFilePath = std::tmpnam(nullptr);
char buf[L_tmpnam];
tmpnam_s(buf); //tmpnam_s定义于stdio.h中,tmpnam在std::中
tempFilePath = buf;
std::ofstream tempFile(tempFilePath, std::ios::binary);
if (!tempFile.is_open()) {
std::cerr << "Error: Cannot create temporary file" << std::endl;
return false;
}
tempFile.write(reinterpret_cast<const char*>(byteArray.data()), byteArray.size());
tempFile.close();
return true;
}
// 获取临时文件路径
std::string getTempFilePath() const {
return tempFilePath;
}
// 删除临时文件
void cleanupTempFile() {
if (!tempFilePath.empty()) {
std::remove(tempFilePath.c_str());
tempFilePath.clear();
}
}
// 获取字节数组大小
size_t getByteArraySize() const {
return byteArray.size();
}
};

浙公网安备 33010602011771号