Oracle Solaris Studio 12.2:C++ 用户指南

13.4.1.5 在文件内重新定位

您可以在文件中改变读取和写入的位置。有多个工具可以达到这个目的。


enum seek_dir {beg=0, cur=1, end=2};

例如,给定 fstream aFile


streampos original = aFile.tellp();     //save current position
aFile.seekp(0, ios::end); //reposition to end of file
aFile << x;               //write a value to file
aFile.seekp(original);    //return to original position

seekg (seekp) 可以采用一个或两个参数。如果有两个参数,第一个参数是相对于 seek_dir 值(也就是第二个参数)指示的位置的位置。例如:


aFile.seekp(-10, ios::end);

从终点移动 10 个字节


aFile.seekp(10, ios::cur);

从当前位置向前移 10 个字节。


注 –

并不能方便地在文本流中进行任意查找,但总是可以返回到以前保存的 streampos 值。