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

dfty9e19  于 2024-01-09  发布在  其他
关注(0)|答案(2)|浏览(136)

我有一个二进制文件,假设在字节11到字节14,代表一个整数= 100。现在我想替换整数值= 200,而不是现有的一个。
我怎么能用C++来做呢?谢谢T。

jv4diomz

jv4diomz1#

Google是你的朋友。搜索“C++二进制文件”会给你给予一些有用的页面,比如:This useful link
简而言之,你可以这样做:

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

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

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


结合这两个和调整您的特定需求应该不会太难。

展开查看全部
ffvjumwh

ffvjumwh2#

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

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

字符串

**注意:**请确保在打开文件时不要使用std::ios::app模式,否则所有的写操作都会被添加到文件的末尾(尾部)。

相关问题