tellg

tellg()和tellp()是C++檔案流操作中獲得流指針的函式。

基本介紹

釋義,和tellp區分,tellg函式,函式定義,函式說明,函式示例,

釋義

所有輸入/輸出流對象(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;
}

相關詞條

熱門詞條

聯絡我們