tellg()和tellp()


tellg()(和tellp() ) 是 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.tellp();
fout.put(str[k]);
cout <<” “<<str[k]<<endl;
}
fout.close();
输出:
File point:0 t
File point:1 e
File point:2 s
File point:3 t
下例使用这些函数来获得一个二进制文件的大小:
// obtaining file size
#include <iostream.h>
#include <fstream.h>
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;
}

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值