zoukankan      html  css  js  c++  java
  • 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;
    }

  • 相关阅读:
    CF766 ABCDE
    CF767 C.Garland DFS
    CF767 B. The Queue 贪心+细节
    CF767 A. Snacktower 暴力
    CF760 D Travel Card 简单DP
    CF760 C. Pavel and barbecue 简单DFS
    CF758 D. Ability To Convert 细节处理字符串
    ZOJ 3787 Access System 水
    ZOJ 3785 What day is that day?
    ZOJ 3782 G
  • 原文地址:https://www.cnblogs.com/pamxy/p/2991498.html
Copyright © 2011-2022 走看看