C++在特定位置的文件中覆盖数据

kar*_*boy 10 c++ file-io

我在用c ++重写文件中的某些数据时遇到问题.使用的代码是

 int main(){
   fstream fout;
   fout.open("hello.txt",fstream::binary | fstream::out | fstream::app);
   pos=fout.tellp();
   fout.seekp(pos+5);
   fout.write("####",4);
   fout.close();
   return 0;
Run Code Online (Sandbox Code Playgroud)

}

问题是甚至在使用seekp之后,数据总是写在最后.我想把它写在特定的位置.如果我不添加fstream :: app,文件的内容将被删除.谢谢.

Eli*_*ser 13

问题在于fstream::app- 它打开文件以进行追加,这意味着所有写入都将转到文件的末尾.为了避免内容被删除,请尝试打开fstream::in,意思是打开fstream::binary | fstream::out | fstream::in.

  • 如果同时使用`fstream :: in`和`fsteam :: out`,你将打开文件进行读写 - 这意味着它将被打开以进行写入而不删除以前的内容. (2认同)

Rob*_*b K 5

你想要类似的东西

fstream fout( "hello.txt", fstream::in | fstream::out | fstream::binary );
fout.seek( offset );
fout.write( "####", 4 );
Run Code Online (Sandbox Code Playgroud)

fstream::app告诉它在每次输出操作之前移至文件末尾,因此,即使您显式查找到某个位置,执行write()(即seekp( 0, ios_base::end );)时,写入位置也会被强制移至文件末尾。

cf. http://www.cplusplus.com/reference/iostream/fstream/open/

要注意的另一件事是,由于您使用打开了文件fstream::app,因此tellp()应返回文件的结尾。因此seekp( pos + 5 )应该尝试超越当前文件位置的结尾。