zoukankan      html  css  js  c++  java
  • seek()和tell()在文件里转移

    Seek()方法允许在输入和输出流移动到任意的位置,seek()有好几种形式。包含:seekp()

    方法和seekg()方法,p是put的意思,g是get的意思;其中输入流里用seekg()函数,输出流里用seekp()函数;

    Seekp()和seekg()有两个重载,第一个是:接受一个参数,接受一个绝对位置,

    第二个是接受接受有一个移动位置,第二个参数是起始点。

    位置 说明
    std::ios_base::beg 定位到流的开头
    std::ios_base::cur  定位到流的当前位置
    std::ios_base::end 定位到流的结尾
    #include <iostream>
    #include <fstream>
    /* run this program using the console pauser or add your own getch, system("pause") or input loop */
    
    int main(int argc, char** argv) 
    {
        std::ofstream fout("text.out");
        if(!fout)
        {
            std::cerr << "Error openging the text.out for writing" << std::endl;
        }
        
        fout << "12345";
        std::ios_base::streampos curPos = fout.tellp();
        if(curPos == 5)
        {
            std::cout << "curPos is 5" << std::endl;
        }else
        {
            std::cout << "curPos is not 5" << std::endl;
        }
        
        fout.seekp(2,std::ios_base::beg);
        fout << 0;
        fout.close();
        
        //text.out is 12045
        
        std::ifstream fin("text.out");
        if(!fin)
        {
            std::cerr << "Error openging the text.out for reading" << std::endl;
            return 1;
        }
         
        int textVal;
        fin >> textVal;
        std::cout << textVal << std::endl;
        
        return 0;
    }

    最后i的textVal是12045

  • 相关阅读:
    Qt 添加外部库文件
    实例属性的增删改查
    面向对象2 类属性的增删改查
    面向对象
    hashlib模块
    configparser模块
    logging模块
    re模块2
    计算器 暂时没解决小数问题
    re正则表达式
  • 原文地址:https://www.cnblogs.com/boost/p/10359091.html
Copyright © 2011-2022 走看看