先说一下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;