先說一下C語言中fseek()的功能:
函數原型:int fseek(FILE *fp, LONG offset, int origin)
參數含義:fp 文件指針 offset 相對於origin規定的偏移位置量 origin 指針移動的起始位置,可設置為以下三種情況: SEEK_SET 文件開始位置 SEEK_CUR 文件當前位置 SEEK_END 文件結束位置
C++中seep()和seekg()函數功能
seekp:設置輸出文件流的文件流指針位置
seekg:設置輸入文件流的文件流指針位置
函數原型:
ostream& seekp( streampos pos );
ostream& seekp( streamoff off, ios::seek_dir dir );
istream& seekg( streampos pos );
istream& seekg( streamoff off, ios::seek_dir dir );
函數參數
pos:新的文件流指針位置值
off:需要偏移的值
dir:搜索的起始位置
dir參數用於對文件流指針的定位操作上,代表搜索的起始位置
在ios中定義的枚舉類型:
enum seek_dir {beg, cur, end};
每個枚舉常量的含義:
ios::beg:文件流的起始位置
ios::cur:文件流的當前位置
ios::end:文件流的結束位置
轉載至http://blog.sina.com.cn/s/blog_679f85d40100mysi.html
補充:經過自己調試,發現文件指針有個特性,一旦指針到達文件末尾,就無法再將指針指向文件其他位置,如以下兩段代碼:
string str; srcin.seekg(0, ios::end); getline(srcin, str); cout << str << endl; //無輸出 srcin.seekg(0, ios::beg); getline(srcin, str); //無輸出
string str; srcin.seekg(10, ios::beg); getline(srcin, str); cout << str << endl; //有輸出 srcin.seekg(0, ios::beg); getline(srcin, str); //有輸出 cout << str << endl;