首页 > 解决方案 > 如何使用 C++ 覆盖二进制文件的一部分?

问题描述

我有一个二进制文件,假设在字节 11 到字节 14,表示整数 = 100。现在我想替换那个整数值 = 200 而不是现有的。

如何使用 C++ 做到这一点?谢谢T。

标签: c++filebinaryfstreamoverwrite

解决方案


谷歌是你的朋友。搜索“C++ 二进制文件”会给你一些有用的页面,例如:这个有用的链接

简而言之,您可以执行以下操作:

int main() 
{ 
  int x; 
  streampos pos; 
  ifstream infile; 
  infile.open("silly.dat", ios::binary | ios::in); 
  infile.seekp(243, ios::beg); // move 243 bytes into the file 
  infile.read(&x, sizeof(x)); 
  pos = infile.tellg(); 
  cout << "The file pointer is now at location " << pos << endl; 
  infile.seekp(0,ios::end); // seek to the end of the file 
  infile.seekp(-10, ios::cur); // back up 10 bytes 
  infile.close(); 
} 

这适用于阅读。要打开文件进行输出:

ofstream outfile;
outfile.open("junk.dat", ios::binary | ios::out);

将这两者结合起来并根据您的特定需求进行调整应该不会太难。


推荐阅读