Сохраните двоичный файл, преобразованный в массив C-Style, в массив char - PullRequest
0 голосов
/ 10 октября 2018

Я использую метод для чтения файлов и открытия его.Этот метод принимает в качестве аргумента один массив, соответствующий файлу, преобразованному в C-массив.Я могу создать этот массив следующим образом:

unsigned char dataArray[24] = {
    0x4D, 0x5A, 0x90, 0x00, 0x03, 0x00, 0x00, 0x00, 0x04, 0x00, 0x00, 0x00,
    0xFF, 0xFF, 0x00, 0x00, 0xB8, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
};

Если я вызываю мой метод с этим массивом, он работает.Я получил код C-Style в файле output.txt благодаря приведенному ниже коду.Я хотел бы сейчас выбрать файл, прочитать его и динамически заполнить мой dataArray без необходимости писать C-стиль в .txt и копировать / вставлять его в исходный код.Я знаю, что сгенерированный C-стиль является правильным, потому что я могу поместить его прямо в мой исходный код, и он работает.Проблема в том, что если я хочу заполнить dataArray и вызвать его напрямую, файл не может быть прочитан.Возможно, байты повреждены или неправильно заполнены в массиве.Я не знаю, в чем проблема в моем коде.Надеюсь, вы поможете мне.

#include "pch.h"
#include <fstream>
#include <iostream> // Standard C++ library for console I/O
#include <string> // Standard C++ Library for string manip
#include <Windows.h> // WinAPI Header
#include <TlHelp32.h> //WinAPI Process API
#include <stdio.h>
#include <assert.h>
#include <sstream>
#include <vector>
#include <iomanip>
#include <bitset>
#include <cstdlib>
#include <iterator>
#include <memory>
#include <cstring>



void readFile(std::string p_path, unsigned char* p_dataArray[]);

unsigned char * dataArray[1];

int main()
{

    std::string path = "The\\Path\\To\\My.exe";
    readFile(path,dataArray);
}

void readFile(std::string p_path, unsigned char* p_dataArray[])
{
    std::ifstream input{ p_path, std::ios::binary };
    if (!input.is_open()) {
        std::cout << "Error: Couldn't open\"" << p_path << "\" for reading!\n\n";
    }

    // read the file into a vector
    std::vector<unsigned char> data{ std::istream_iterator<unsigned char>{ input },
                                     std::istream_iterator<unsigned char>{} };

    std::ostringstream oss;  // use a stringstream to format the data

    int columnCounter = 0;
    for (int i = 0; i < data.size(); i++)
    {
        columnCounter++;
        if (columnCounter == 8) {
            columnCounter = 0;
            oss << " " << std::endl;
        }
        if (i == i - 1)
        {
            oss << '0'
                << 'x'
                << std::setfill('0') << std::setw(2) << std::uppercase << std::hex << static_cast<int>(data.at(i));
        }
        else
        {
            oss << '0'
                << 'x'
                << std::setfill('0') << std::setw(2) << std::uppercase << std::hex << static_cast<int>(data.at(i)) << ',';
        }

    }

    // create a unique_ptr and allocate memory large enough to hold the string:
    std::unique_ptr<unsigned char[]> memblock{ new unsigned char[oss.str().length() + 1] };

    // copy the content of the stringstream:
    int r = strcpy_s(reinterpret_cast<char*>(memblock.get()), oss.str().length() + 1, oss.str().c_str());

    std::ofstream myfile;
    myfile.open("output.txt");
    myfile << oss.str();
    myfile.close();


    readMyFile(memblock.get());
}
...