输入流操作: seekg (和tellg )。
输出流操作: seekp ()和tellp ) )。
以输入流函数为例说明使用方法。
seekg ) )是输入文件的定位,有两个参数。 第一个参数是偏移,第二个参数是基址。
第一个参数可以是正值或负值。 正值向后偏移,负值向前偏移。 第二个参数如下:
ios:beg :表示输入流开始位置
ios:cur :表示输入流的当前位置
ios:end :表示输入流结束位置
tellg ) )函数不需要带参数,返回当前位置指针的位置,并表示输入流的大小。
假设文件test。 txt包括:
你好,my world
name:hehonghua
date:20090902
方案如下:
#include iostream
#包含fstream
#include assert.h
用户命名空间STD;
int main () )
{
ifstreamin(test.txt );
资产(in;
in.seekg(0,ios:end; //基地址在文件末尾,偏移地址为0,指针在文件末尾
streampos sp=in.tellg (; //sp是锚点指针,位于文件末尾,因此是文件的大小
cout'file size:'endlspendl;
in.seekg(-sp/3,ios:end ); //基地址在文件末尾,偏移地址为负,因此移动到sp/3字节处
streampos sp2=in.tellg (;
cout ' from file topoint : ' endl sp2endl;
in.seekg(0,ios:beg ); //基地址为文件头部,偏移为0,被定位在文件头部
coutin.rdbuf (; //从头读文件的内容
in.seekg(sp2;
coutin.rdbuf () endl; 从//sp2读取文件内容
返回0;
}
输出结果。
文件大小:
45
来自文件至点:
30
你好,my world
name:hehonghua
date:20090902
date:20090902
int main () )
{
//获得文件大小: c方式
ifstream ifs;
ifs.open(log.txt );
资产(ifs.is _ open );
ifs.seekg(0,std:ios:end;
coutifs.tellg () endl;
ifs.close (;
//获得文件大小: c方式
file*FP=fopen('log.txt ',' rb ' );
assert(0==fseek ) FP,0,SEEK_END );
unsignedintusize=FP;
coutusizeendl;
流量(FP );
返回0;
}
转载于:https://www.cn blogs.com/kex1n/archive/2011/01/28/2286423.html