使用库更新文件<fstream>(仅覆盖特定部分)

Updating a file with <fstream> library (overwriting just a specific section)

本文关键字:覆盖 定部 fstream 更新 文件 lt gt      更新时间:2023-10-16

我想问一下是否有任何方法可以更新内容为"ooooo"的文本文件"ooXXo"使用fstream库。我知道cstdio有一种方法,但我不想使用它,因为它不支持异常处理…此外,我不想将文件读取到内存,更新我想要的部分,然后将所有内容写入干净的文件…基本上,我正在寻找一种方法来做到这一点与fstream:

/* fseek example */
#include <stdio.h>
int main ()
{
  FILE * pFile;
  pFile = fopen ( "example.txt" , "w" );
  fputs ( "This is an apple." , pFile );
  fseek ( pFile , 9 , SEEK_SET );
  fputs ( " sam" , pFile );
  fclose ( pFile );
  return 0;
}
#include <fstream>
int main()
{
    std::ofstream os("example.txt");
    os<<"This is an apple.";
    os.seekp(9);
    os<<" sam";
    return 0;
}
#include <fstream>
int main (){
  std::fstream pFile("example.txt");
  pFile << "This is an apple.";
  pFile.seekp(9);
  pFile << "sam";
  pFile.close();
  return 0;
}

fstream默认打开文件进行读写。在构造函数中还有一个带默认值的参数,用来控制该行为。