2024年8月22日

將檔案所有bytes 轉為C語言unsigned char 陣列



#include <math.h> #include <iostream> #include <string> #include <vector> #include <sstream> void generateUnsignedCharArray(const char* inputFile, const char* outputFilePrefix) { FILE* inFile; if (fopen_s(&inFile, inputFile, "rb") != 0) { perror("Error opening input file"); return; } fseek(inFile, 0, SEEK_END); long fileSize = ftell(inFile); fseek(inFile, 0, SEEK_SET); unsigned char* buffer = (unsigned char*)malloc(fileSize); if (buffer == NULL) { perror("Memory allocation error"); fclose(inFile); return; } fread(buffer, 1, fileSize, inFile); fclose(inFile); char outFileName[256]; snprintf(outFileName, sizeof(outFileName), "%s", outputFilePrefix); FILE* outFile; if (fopen_s(&outFile, outFileName, "w") != 0) { perror("Error opening output file"); free(buffer); return; } fprintf(outFile, "unsigned char datas[] = {"); for (long i = 0; i < fileSize; i++) { fprintf(outFile, "0x%02X", buffer[i]); if (i < fileSize - 1) fprintf(outFile, ", "); } fprintf(outFile, "};\n"); fprintf(outFile, "size: %ld\n", fileSize); fclose(outFile); free(buffer); } int main(int argc, char* argv[]) { if (argc !=3) { return 1; } const char* inputFile = argv[1]; const char* outputFilePrefix = argv[2]; generateUnsignedCharArray(inputFile, outputFilePrefix); return 0; }

沒有留言:

張貼留言