【问题标题】:How to overwrite a portion of a binary file using C++?如何使用 C++ 覆盖二进制文件的一部分?
【发布时间】:2021-09-25 02:48:13
【问题描述】:

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

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

【问题讨论】:

  • 你尝试过什么,为什么失败了?
  • 我不知道如何移动到二进制文件的特定位置。另外,我不确定我是否使用命令 f.write() 它会覆盖现有内容,或附加到该位置。
  • 在您了解write 的相同位置查找fseek。如果您寻找某个位置并调用write,输出将转到您移动到的当前位置。
  • 你看过the manual吗?

标签: c++ file binary fstream overwrite


【解决方案1】:

Google 是您的朋友。搜索“C++二进制文件”会给你一些有用的页面,比如:This useful link

简而言之,你可以这样做:

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);

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

【讨论】:

    猜你喜欢
    • 2011-11-09
    • 2013-01-10
    • 1970-01-01
    • 1970-01-01
    • 2011-03-31
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多