V
V
VirusesAnalystCoder2020-06-27 18:54:17
C++ / C#
VirusesAnalystCoder, 2020-06-27 18:54:17

How to write hex to file?

Hello.
There is this code:

string ToHex(const string& s, bool upper_case)
{
    ostringstream ret;

    for (string::size_type i = 0; i < s.length(); ++i)
        ret << hex << setfill('0') << setw(2) << (upper_case ? uppercase : nouppercase) << (int)s[i];

    return ret.str();
}

int main(int argc, char* argv[]) {
    ifstream::pos_type size;
    char * memblock;

    ifstream file ("program1.cs", ios::in|ios::binary|ios::ate);
    if (file.is_open())
    {
        size = file.tellg();
        memblock = new char [size];
        file.seekg (0, ios::beg);
        file.read (memblock, size);
        file.close();
    }
    string read_bytes = ToHex(memblock, true);
    cout << read_bytes << endl;

    string need_replace = "707269766174";
    size_t pos = read_bytes.find(need_replace);

    read_bytes.replace(pos, need_replace.length(), "7075626C6963");

    ofstream replaced("rep.cs");
    replaced << read_bytes; // ТУТ НУЖНА ПРАВИЛЬНАЯ ЗАПИСЬ В ФАЙЛ
    replaced.close();

    getchar();
}

But the thing is, after writing to the file, I get the text, not the desired hex.
That is, according to the code, I replace 707269766174the hex address with 7075626C6963. This address contains the word "privat". I will convert it to hex "public". But the output I get is not "public" converted from hex, but just HEX in the text. That is, the file contains this: "7075626C6963" ... I hope I managed to explain.
Help))

Answer the question

In order to leave comments, you need to log in

2 answer(s)
V
VirusesAnalystCoder, 2020-06-27
@VirusesAnalystCoder

Decided!
It was required to convert string, in which hex is located, to unsigned char*or unsigned char[], then write to a file in binary mode.

A
Alexander Ananiev, 2020-06-27
@SaNNy32

Need to write to a file opened in binary mode for writing

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question