如何使用 C++ 覆盖二进制文件的一部分?

问题描述 投票:0回答:2

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

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

c++ file binary fstream overwrite
2个回答
1
投票

谷歌是你的朋友。搜索“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);

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


0
投票

这个过程有点棘手。让我在代码片段和注释的帮助下写下所需的步骤:

  // Open a file to write. Use both ios::out and ios::in. If you dont 
  // use ios::in then file will get truncated.
  fstream outputfile("data.dat", std::ios::binary | std::ios::out | ios::in );
  if(outputfile.is_open())
  {
    int value{200}; //value to be written
    outputfile.seekp(10); //As we desired to overwrite from 11th byte
    outputfile.write((char*)(&value), sizeof(int)); //4 bytes will be replaced
    outputfile.close();
  }

**注意:**打开文件时请确保不要使用

std::ios::app
模式,否则所有写入操作最终都会添加到文件末尾(尾部)。

© www.soinside.com 2019 - 2024. All rights reserved.