1

I'm trying to read in an .exe and write it back out. My code works with .txt files but for some reason it is breaking executables. What am I doing wrong? I'm not sure if I am reading it wrong or writing it wrong..

#include <string>
#include <vector>
#include <iostream>
#include <filesystem>
#include <unordered_set>

#include <Windows.h>

unsigned char *ReadFileAsBytes(std::string filepath, DWORD &buffer_len)
{
    std::ifstream ifs(filepath, std::ofstream::binary | std::ifstream::ate);
    if (!ifs.is_open())
    {
        return(nullptr);
    }

    // Go To End
    ifs.seekg(0, ifs.end);

    // Get Position (Size)
    buffer_len = static_cast<DWORD>(ifs.tellg());

    // Go To Beginning
    ifs.seekg(0, ifs.beg);

    // Allocate New Char Buffer The Size Of File
    PBYTE buffer = new BYTE[buffer_len];

    ifs.read(reinterpret_cast<char*>(buffer), buffer_len);
    ifs.close();

    return buffer;
}

void WriteToFile(std::string argLocation, unsigned char *argContents, int argSize)
{
    std::ofstream myfile;
    myfile.open(argLocation);
    myfile.write((const char *)argContents, argSize);
    myfile.close();
}

int main()
{
    // Config
    static std::string szLocation   = "C:\\Users\\Admin\\Desktop\\putty.exe";
    static std::string szOutLoc     = "C:\\Users\\Admin\\Desktop\\putty2.exe";

    DWORD dwLen;
    unsigned char *szBytesIn = ReadFileAsBytes(szLocation, dwLen);

    std::cout << "Read In " << dwLen << " Bytes" << std::endl;

    // Write To File
    WriteToFile(szOutLoc, szBytesIn, dwLen);

    system("pause");
}

1 Answer 1

3

You open input file in binary mode, but in this code

std::ofstream myfile;
myfile.open(argLocation);

you open output file without binary mode. And there is no reason to call open separately:

std::ofstream myfile( argLocation, std::ios::out | std::ios::binary | std::ios::trunc);
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.