开发者

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

I want to ask if there is any way to update say a text file with a content of "ooooo" to "ooXXo" using the fstream library. I know there is a way with cstdio but I don't want to use that one because of unsupported exception handling... Also, I don't want to read the file to memory, update the section I want and then write everything to a clean file...basically I'm looking for a way to do this with fstream:

开发者_JAVA百科
/* 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 by default opens the file for both reading and writing. There's a second argument with a default value in the constructor which controls that behavior.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜