我知道如果要定位ifstream的位置可以用诸如ifstream.seekg(offset, ios::cur)这样的方法,但是我想知道ifstream当前读取的位置怎么写呢?这是个现实的需求,我必须先得到这个位置,然后读取线程退出,再启动读取线程时用上面的seekg方法定位到之前的位置继续读取下去,我觉得这是一个挺普通的功能需求,ifstream类应该已经提供了现成方法的吧??怎么写呢?望高手指教!
tellg()函数不需要带参数,它返回当前定位指针的位置,也代表着输入流的大小。
#include <iostream>
#include <fstream>
#include <assert.h>
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;
}