新闻资讯
看你所看,想你所想

tellg

tellg

tellg()和tellp()是C++档案流操作中获得流指针的函式。

基本介绍

  • 中文名:tellg
  • 性质:C++档案流
  • 获得:获得流指针
  • 类别:函式

释义

所有输入/输出流对象(i/o streams objects)都有至少一个流指针:
· ifstream, 类似istream, 有一个被称为get pointer 的指针,指向下一个将被读取的
元素。
· ofstream, 类似ostream, 有一个指针put pointer ,指向写入下一个元素的位置。
· fstream, 类似iostream, 同时继承了get 和put
我们可以通过使用以下成员函式来读出或配置这些指向流中读写位置的流指针:

和tellp区分

这两个成员函式不用传入参数,返回pos_type 类型的值(根据ANSI-C++ 标準) ,
就是一个整数,代表当前get 流指针的位置(用tellg) 或put 流指针的位置(用
tellp).而且不要对tellg 或tellp 的返回值进行修改。

tellg函式

函式定义

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;
}

转载请注明出处海之美文 » tellg

相关推荐

    声明:此文信息来源于网络,登载此文只为提供信息参考,并不用于任何商业目的。如有侵权,请及时联系我们:ailianmeng11@163.com