c++ - 修改二进制文件

标签 c++ visual-c++

我正在尝试编写一个小程序,它将在二进制文件中搜索几个字节并将其替换为另一组字节。但每次我尝试运行这个小应用程序时,我都会收到有关istream_iterator is not dereferenceable 的消息。 也许有人建议如何以另一种方式做到这一点(迭代器对我来说是一个新主题)。

#include <fstream>
#include <iterator>
#include <algorithm>

using namespace std;

int main() {

typedef istream_iterator<char> input_iter_t;

const off_t SIZE = 4;
char before[SIZE] = { 0x12, 0x34, 0x56, 0x78 };
char  after[SIZE] = { 0x78, 0x12, 0x34, 0x65 };

fstream filestream("numbers.exe", ios::binary | ios::in | ios::out);

if (search(input_iter_t(filestream), input_iter_t(), before, before + SIZE) != input_iter_t()) {
    filestream.seekp(-SIZE, ios::cur);
    filestream.write(after, SIZE);
}

return 0;
}

这是我第二次尝试这样做,但还是出了点问题。小文件看起来工作正常,但大文件(大约 2MB)工作非常缓慢,永远找不到我正在寻找的模式。

#include <iostream>
#include <cstdlib>
#include <string>
#include <fstream>
#include <iterator>
#include <vector>
#include <algorithm>
#include <windows.h>

using namespace std;

int main() {

const off_t Size = 4;
unsigned char before[Size] = { 0x12, 0x34, 0x56, 0x78 };
unsigned char  after[Size] = { 0x90, 0xAB, 0xCD, 0xEF };

    vector<char> bytes;
    {
        ifstream iFilestream( "numbers.exe", ios::in|ios::binary );
        istream_iterator<char> begin(iFilestream), end;
        bytes.assign( begin, end ) ;
    }

    vector<char>::iterator found = search( bytes.begin(), bytes.end(), before, before + Size );
    if( found != bytes.end() )
    {
        copy( after, after + Size, found );
        {
            ofstream oFilestream( "number-modified.exe" );
            copy( bytes.begin(), bytes.end(), ostream_iterator<unsigned char>(oFilestream) );
        }
    }
return 0;
}

干杯, 托马斯

最佳答案

将文件的较大部分读入内存,在内存中替换它,然后将文件堆转储到磁盘。一次读取一个字节非常很慢。

我还建议您阅读有关 mmap(或 Win32 中的 MapViewOfFile)的内容。

关于c++ - 修改二进制文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1751929/

相关文章:

c++ - 编写通用包装器 : Conditionally Map different Types from Template Arguments onto a Single Class-Internal Type

c++ - LNK1113 : invalid machine type 0x1C0

c++ - 如何为匿名命名空间中未引用的本地函数生成警告?

c++ - boost::asio async_send 错误

c++ - 如何简洁地将一个数组的范围分配给另一个数组的范围?

C++ boost::mpl::type 前向声明

c++ - MFC中如何使用_beginthreadex

windows - 我如何在 Windows XP 上部署 Qt 5.10 Quick 2 应用程序?

C++ 如何将对象指针发送到函数(对指针列表进行排序)

c++ - 为什么这是一个最终递归可变参数宏?