您可以在文件中改变读取和写入的位置。有多个工具可以达到这个目的。
tellg (tellp) 是报告文件位置的 istream (ostream) 成员函数。因为 istream 和 ostream 是 fstream 的父类,所以 tellg 和 tellp 还可以作为 fstream 类的成员函数调用。
seekg (seekp) 是查找给定位置的 istream (ostream) 成员函数。
seek_dir enum 指定相对位置以用于 seek。
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 值。