2017-02-10 91 views
1

我試圖在.exe中讀取並將其寫回。我的代碼適用於.txt文件,但由於某種原因,它正在破壞可執行文件。我究竟做錯了什麼? 我不知道如果我讀錯了或寫錯..讀取二進制文件w/ifstream

#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"); 
} 

回答

3

您打開輸入文件以二進制模式,但在此代碼

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

你打開輸出文件沒有二進制模式。並且沒有理由分開打開:

std::ofstream myfile(argLocation, std::ios::out | std::ios::binary | std::ios::trunc);