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

 

转载于:https://www.cnblogs.com/boost/p/10359091.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值