對輸入流操作:seekg()與tellg()
對輸出流操作:seekp()與tellp()
下面以輸入流函數為例介紹用法:
seekg()是對輸入文件定位,它有兩個參數:第一個參數是偏移量,第二個參數是基地址。
對於第一個參數,可以是正負數值,正的表示向后偏移,負的表示向前偏移。而第二個參數可以是:
ios::beg:表示輸入流的開始位置
ios::cur:表示輸入流的當前位置
ios::end:表示輸入流的結束位置
tellg()函數不需要帶參數,它返回當前定位指針的位置,也代表着輸入流的大小。
假設文件test。txt為以下內容:
hello,my world
name:hehonghua
date:20090902
程序為:
#include
#include
#include
using namespace std;
int main()
{
ifstream in("test.txt");
assert(in);
in.seekg(0,ios::end); //基地址為文件結束處,偏移地址為0,於是指針定位在文件結束處
streampos sp=in.tellg(); //sp為定位指針,因為它在文件結束處,所以也就是文件的大小
cout<<"file size:"<<endl<<sp<<endl;
in.seekg(-sp/3,ios::end); //基地址為文件末,偏移地址為負,於是向前移動sp/3個字節
streampos sp2=in.tellg();
cout<<"from file to point:"<<endl<<sp2<<endl;
in.seekg(0,ios::beg); //基地址為文件頭,偏移量為0,於是定位在文件頭
cout<<in.rdbuf(); //從頭讀出文件內容
in.seekg(sp2);
cout<<in.rdbuf()<<endl; //從sp2開始讀出文件內容
return 0;
}
則結果輸出:
file size:
45
from file to point:
30
hello,my world
name:hehonghua
date:20090902
date:20090902
