tellg()和tellp()是C++文件流操作中获得流指针的函数。
tellg
中文名
tellg性质
C++文件流获得
获得流指针类别
函数释义
所有输入/输出流对象(i/o streams objects)都有至少一个流指针:
·ifstream,类似istream,有一个被称为get pointer的指针,指向下一个将被读取的
元素。
·ofstream,类似ostream,有一个指针put pointer,指向写入下一个元素的位置。
·fstream,类似iostream,同时继承了get和put
我们可以通过使用以下成员函数来读出或配置这些指向流中读写位置的流指针:
tellg和tellp区分
这两个成员函数不用传入参数,返回pos_type类型的值(根据ANSI-C++标准),
就是一个整数,代表当前get流指针的位置(用tellg)或put流指针的位置(用
tellp).而且不要对tellg或tellp的返回值进行修改。
tellg(io)函数
函数定义
pos_type tellg();
函数说明
用于输入流,返回流中‘get’指针当前的位置。
函数示例
ifstream file;
char c;
streamoff i;
file.open("basic_istream_tellg.txt");//文件内容:0123456789
i=file.tellg();
file>>c;
cout<<c<<""<<i<<endl;
输出:
0 0
tellp(io)函数
函数定义
pos_type tellp();
函数说明
用于输出流,返回当前流中‘put’指针的位置。
函数示例
string str(“test”);
ofstream fout(“e:output.txt”);
int k;
for(k=0;k<str.length();k++)
{cout<<”File point:”<fout.put(str[k]);cout<<”“<}
fout.close();
输出:
File point:0 t
File point:1 e
File point:2 s
File point:3 t
下例使用这些函数来获得一个二进制文件的大小:
//obtaining file size
#include
#include
const char*filename="example.txt";
int main(){
long l,m;
ifstream file(filename,
ios::in|ios::binary);
l=file.tellg();
file.seekg(0,ios::end);
m=file.tellg();
file.close();
cout<<"size of"<<filename;
cout<<"is"<<(m-l)<<"
bytes.n";
return 0;}
参考资料
tellg用法·CSDN