Warning: file_get_contents(/data/phpspider/zhask/data//catemap/6/cplusplus/157.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C++ 使用库更新文件(仅覆盖特定部分)_C++_File_Fstream_Overwrite - Fatal编程技术网

C++ 使用库更新文件(仅覆盖特定部分)

C++ 使用库更新文件(仅覆盖特定部分),c++,file,fstream,overwrite,C++,File,Fstream,Overwrite,我想问一下,是否有任何方法可以更新一个内容为ooo to的文本文件 ooXXo使用fstream库。我知道cstdio有一种方法,但我不想使用这种方法,因为不支持异常处理。。。此外,我不想将文件读入内存,更新我想要的部分,然后将所有内容写入一个干净的文件…基本上,我正在寻找一种使用fstream实现这一点的方法: /* fseek example */ #include <stdio.h> int main () { FILE * pFile; pFile = fopen

我想问一下,是否有任何方法可以更新一个内容为ooo to的文本文件 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;
}

默认情况下,fstream会打开文件进行读取和写入。构造函数中还有第二个参数具有默认值,用于控制该行为。

您应该在流上调用close。它将在操作系统的析构函数中自动调用,但到那时,如果出现异常,它将被吞没。@K-ballo:当然,这段代码中没有任何错误检查,但我只是按照最初的示例执行。而且,无论如何,我不明白你的意思:流对象本身不会抛出,除非你显式地为它启用异常;而且,即使它确实存在,比如说一个来自内部缓冲区的std::bad_alloc,在这个示例代码中没有try块,所以即使我调用close,异常也将不被处理,并导致调用terminate,这在这里无论如何都会发生。。。或者我遗漏了什么?不,只是觉得值得一提的是,还有一个相当于fclose的东西,它并不总是意味着让析构函数为你做。嗯,好的,虽然我通常倾向于避免关闭,而是将文件流对象的范围限制在需要它们存在的代码部分,有点像C中的using语句,由于根本不存在try-catch块,因此无法保证将调用terminate。一般来说,如果您只需要读或写访问权限,您可能应该使用ifstream/ofstream使其更加清晰。是的,但您将无法更新已经存在的文件,我想这就是01d55的要点。。。如果使用ios::out标志以ofstream或FSSTREAM的形式打开文件,它将清除文件中的所有现有内容,以更新不带ios::out的FSSTREAM文件。感谢您的回复;实际上,如果还设置了二进制标志,则需要两个标志,如:ios::in | ios::out。。。
#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;
}