【问题标题】:Reading Binary Files w/ ifstream使用 ifstream 读取二进制文件
【发布时间】:2017-06-28 06:40:04
【问题描述】:

我正在尝试读取 .exe 并将其写回。我的代码适用于 .txt 文件,但由于某种原因,它会破坏可执行文件。我究竟做错了什么? 不知道是看错了还是写错了..

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

【问题讨论】:

    标签: c++ io stl


    【解决方案1】:

    您以二进制模式打开输入文件,但在此代码中

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

    您在没有二进制模式的情况下打开输出文件。并且没有理由单独调用 open:

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2013-10-26
      • 2010-12-09
      • 1970-01-01
      • 2013-04-30
      • 2011-09-02
      • 2021-12-04
      • 2019-04-13
      • 2020-11-11
      相关资源
      最近更新 更多