读取带有 ifstream 的二进制文件
Reading Binary Files w/ ifstream
我正在尝试阅读.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");
}
以二进制模式打开输入文件,但在此代码中
std::ofstream myfile;
myfile.open(argLocation);
打开输出文件而不使用二进制模式。并且没有理由单独调用打开:
std::ofstream myfile( argLocation, std::ios::out | std::ios::binary | std::ios::trunc);
相关文章:
- 正在读取二进制文件(is_open)
- 在C++中将类(带有Vector成员)保存为二进制文件
- 如何从二进制文件中读取字符串
- 保存/加载大量短数组到二进制文件
- 从二进制文件中读取整数数组
- Android 在编译二进制文件时重建静态库
- 在 C++ 中将双精度变量写入二进制文件
- clang 的 libFuzzer 可以在同一二进制文件中测试超过 1 个 API 吗?
- C++:实际上不是从二进制文件中读取
- 如何从二进制文件中的给定符号中获取调用程序图
- 将内部带有矢量的结构保存/读取到二进制文件中
- 当与Windows和Linux下的Ifstream相反的二进制文件时,结果不同
- ifstream读取二进制文件在发行模式下工作,但在调试模式下不使用
- 读取带有 ifstream 的二进制文件
- C++:使用std::ifstream读取二进制文件后删除缓冲区/指针时发生访问冲突
- 在二进制文件中从 ifstream 创建unique_ptr
- 使用 ifstream 剂量读取大型二进制文件不会填充字符缓冲区C++
- ifstream从二进制文件中读取的数据与预期不同
- 如何用ifstream和istreambuf_iterator读取二进制文件作为浮点数
- 如何读取用std::ifstream编写的QDataStream二进制文件