zoukankan      html  css  js  c++  java
  • C++利用偏移量对文件操作

    对输入流操作:seekg()与tellg()
    对输出流操作:seekp()与tellp()
    下面以输入流函数为例介绍用法:
    seekg()是对输入文件定位,它有两个参数:第一个参数是偏移量,第二个参数是基地址。
    对于第一个参数,可以是正负数值,正的表示向后偏移,负的表示向前偏移。而第二个参数可以是:
    ios::beg:表示输入流的开始位置
    ios::cur:表示输入流的当前位置
    ios::end:表示输入流的结束位置
    tellg()函数不需要带参数,它返回当前定位指针的位置,也代表着输入流的大小。

    假设文件test。txt为以下内容:
    hello,my world
    name:hehonghua
    date:20090902
    程序为:
    #include
    #include
    #include
    using namespace std;
    int main()
    {
        ifstream in("test.txt");
        assert(in);
        in.seekg(0,ios::end);       //基地址为文件结束处,偏移地址为0,于是指针定位在文件结束处
        streampos sp=in.tellg(); //sp为定位指针,因为它在文件结束处,所以也就是文件的大小
        cout<<"file size:"<<endl<<sp<<endl;

        in.seekg(-sp/3,ios::end); //基地址为文件末,偏移地址为负,于是向前移动sp/3个字节
        streampos sp2=in.tellg();
        cout<<"from file to point:"<<endl<<sp2<<endl;

        in.seekg(0,ios::beg);        //基地址为文件头,偏移量为0,于是定位在文件头
        cout<<in.rdbuf();             //从头读出文件内容
        in.seekg(sp2);

        cout<<in.rdbuf()<<endl; //从sp2开始读出文件内容

        return 0;
    }
    则结果输出:
    file size:
    45
    from file to point:
    30
    hello,my world
    name:hehonghua
    date:20090902

    date:20090902

  • 相关阅读:
    POJ 2947:Widget Factory 求同余方程
    高斯消元几道入门题总结POJ1222&&POJ1681&&POJ1830&&POJ2065&&POJ3185
    POJ 1166:The Clocks
    神经网络 --学习之路,资料汇编
    机器学习 入门资料汇编
    无符号 coredump调试
    CentOS 6.3 升级软件 gcc等,并安装部署DNN环境 (未完成,不完整)
    OpenCL size_t error
    Nervanasys --> pycuda --> installation
    tmux.conf
  • 原文地址:https://www.cnblogs.com/yyxayz/p/4078329.html
Copyright © 2011-2022 走看看