当我尝试获取文件大小时,我有以下块来测试seekg和tellg的行为:
int size = 0;
ifstream in(fileName.c_str(), ifstream::in | ifstream::binary);
if(in)
{
in.seekg(0,ifstream::end);
size = in.tellg();
cout << endl;
cout << endl;
cout << "********** size stream1*** =" << size << endl;
in.seekg(0,ios::end);
size = in.tellg();
cout << "********** size stream2*** =" << size << endl;
in.seekg(0,ios::end);
size = in.tellg();
cout << "********** size stream3*** =" << size << endl;
in.seekg(100,ios::end);
size = in.tellg();
cout << "********** size stream4*** =" << size << endl;
in.seekg(0,ios::beg);
size = in.tellg();
cout << "********** size stream5*** =" << size << endl;
in.seekg(100);
in.seekg(0, ios::end);
size = in.tellg();
cout << "********** size stream6*** =" << size << endl;
in.seekg(100);
in.seekg(0, ios::cur);
size = in.tellg();
cout << "********** size stream7*** =" << size << endl;
in.seekg(-100,ios::end);
size = in.tellg();
cout << "********** size stream8*** =" << size << endl;
in.seekg(ios::beg,ios::end);
size = in.tellg();
cout << "********** size stream9*** =" << size << endl;
in.seekg(ios::beg);
in.seekg(ios::end);
size = in.tellg();
cout << "********** size stream10*** =" << size << endl;
cout << endl;
cout << endl;
}
其结果如下:
********** size stream1*** =1846
********** size stream2*** =1846
********** size stream3*** =1846
********** size stream4*** =1946
********** size stream5*** =0
********** size stream6*** =1846
********** size stream7*** =100
********** size stream8*** =1746
********** size stream9*** =1846
********** size stream10*** =2
我的问题如下:
答案 0 :(得分:4)
好的,我们走了:
tellg()
会产生位置对象,可以回到你所处的位置。返回的类型为std::streampos
,即std::fpos<std::mbstate_t>
。但是,std::fpos<std::mbstate_t>
会转换为std::streamoff
,这是一个整数。基本上,std::streampos
会转换为从第一个位置到当前位置的字符数。0
的{{1}}字符,清楚地将位置设置为文件的开头。您的意思是使用std::ios_base::beg
吗?std::ios_base::cur
将相对于起点,当前位置或结尾,具体取决于 whence 参数为seekg()
,std::ios_base::beg
或std::ios_base::cur
。 std::ios_base::end
类型是枚举,std::ios_base::seekdir
可能具有值std::ios_base::end
。