(源自:http://hi.baidu.com/leoyonn/blog/item/450fd465de279dfaf6365433.html)
對輸入流操作:seekg()與tellg()
對輸出流操作:seekp()與tellp()
下面以輸入流函數為例介紹用法:
seekg()是對輸入文件定位,它有兩個參數:第一個參數是偏移量,第二個參數是基地址。
對於第一個參數,可以是正負數值,正的表示向后偏移,負的表示向前偏移。而第二個參數可以是:
ios::beg:表示輸入流的開始位置
ios::cur:表示輸入流的當前位置
ios::end:表示輸入流的結束位置
tellg()函數不需要帶參數,它返回當前定位指針的位置,也代表着輸入流的大小。
假設文件test。txt為以下內容(所有字符共45個,注意:共有41個字母或標點,有兩個回車,結尾還有兩個字符,目前我還不知道是什么,調試時顯示末尾兩個位置是空的):
hello,my world
name:hehonghua
date:20090902
程序為:
1 #include <iostream> 2 #include <fstream> 3 #include <assert.h> 4 using namespace std; 5 6 int main() 7 { 8 ifstream in("test.txt"); 9 assert(in); 10 in.seekg(0,ios::end); //基地址為文件結束處,偏移地址為0,於是指針定位在文件結束處 11 streampos sp=in.tellg(); //sp為定位指針,因為它在文件結束處,所以也就是文件的大小 12 cout<<"file size:"<<endl<<sp<<endl; 13 in.seekg(-sp/3,ios::end); //基地址為文件末,偏移地址為負,於是向前移動sp/3個字節 14 streampos sp2=in.tellg(); //sp2為30 15 cout<<"from file to point:"<<endl<<sp2<<endl; 16 in.seekg(0,ios::beg); //基地址為文件頭,偏移量為0,於是定位在文件頭 17 cout<<in.rdbuf()<<endl; //從頭讀出文件內容 18 in.seekg(sp2); //這里sp2是絕對位置,與前面的偏移計算無關 19 cout<<in.rdbuf()<<endl; //從sp2開始讀出文件內容 20 return 0; 21 }
則結果輸出:
file size:
45
from file to point:
30
hello,my world
name:hehonghua
date:20090902
date:20090902
