From: http://www.cnblogs.com/kex1n/archive/2011/01/28/2286423.html
对输入流操作:seekg()与tellg() 对输出流操作:seekp()与tellp() 下面以输入流函数为例介绍用法: seekg()是对输入文件定位,它有两个参数:第一个参数是偏移量,第二个参数是基地址。 对于第一个参数,可以是正负数值,正的表示向后偏移,负的表示向前偏移。而第二个参数可以是: ios::beg:表示输入流的开始位置 ios::cur:表示输入流的当前位置 ios::end:表示输入流的结束位置 tellg()函数不需要带参数,它返回当前定位指针的位置,也代表着输入流的大小。
假设文件test。txt为以下内容: hello,my world name:hehonghua date:20090902
程序为: #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; }
则结果输出: file size: 45 from file to point: 30 hello,my world name:hehonghua date:20090902
date:20090902
int main() { //得到文件大小:C++方式 ifstream ifs; ifs.open("log.txt"); assert(ifs.is_open()); ifs.seekg( 0 , std::ios::end ); cout<<ifs.tellg()<<endl; ifs.close();
// 得到文件大小:C方式 FILE* fp = fopen("log.txt", "rb"); assert ( 0 == fseek(fp, 0, SEEK_END)); unsigned int usize = ftell(fp); cout<<usize<<endl; fclose(fp);
return 0; }