zoukankan      html  css  js  c++  java
  • C++ seekp 函数文件流跳转功能产生数据覆盖问题解决

     
    近来,使用C++输出一组数据到文件(*.txt). 需要在输出全部结果后,返回到文件头重新写入一组数据.

        使用seekp函数定位到相关位置:

        seekp函数有两种情况,主要是:

    basic_ostream<_Elem, _Tr>& seekp( pos_type _Pos ); basic_ostream<_Elem, _Tr>& seekp( off_type _Off, ios_base::seekdir _Way );

    其中:

    _Pos
    The position in the stream.

    _Off
    The offset relative to _Way.

    _Way
    One of the ios_base::seekdir enumerations.

    The seekdir type as : static const seekdir beg, cur, end;

    两个情况,分别表示:

    1  跳转到指定位置 : pos_type _Pos  - 字节为跳转单位;

    2  跳转到指定位置,并微调偏移: _way 是需要跳转的位置,有三种即beg-序列(数组,文件流,文件)的开始,

                                                -Off 跳转后位置的偏移量,不可以越界.

    问题: 跳转后,如果跳转到流中间位置,继续打印或者输出新的数据,会出现覆盖旧数据的情况.    

    解决办法是:再要插入新数据的位置处,返回插入之前,提前写入相关的类型相同数目的数据并最好以回车换行做标记.这样跳转到新位置后再直接写入数据覆盖事先写入到该位置的无用数据.

    示例代码: 以下代码,先输入一些数据到txt文件,然后返回到文件起始位置,插入一些新的数据,为了避免覆盖原有数据,提前在起始位置写入了与要插入的数据相同数目相同同类型(或者其类型长度大于要插入类型长度)的数据.

    void FileOperBack(){
        int iNumCounter=0;
        unsigned int recoData=0;
        int recoveryData[6]={0,1,2,3,4,5};
        ofstream testFout("G:\\WorkSpace\\FileOperation\\testFileBackRead.txt");
        for (int i = 0; i < 6; i++)
        {
            testFout<<recoData<<" ";
        }
        testFout<<endl<<endl;
        //testFout<<recoData<<" "<<recoData<<" "<<recoData;
        for (int i = 0; i < 6 ; i++)
        {
            for (int j = 0; j < 6; j++)
            {
                testFout<<i*j<<" ";
                testFout<<flush;
                iNumCounter++;
            }
            testFout<<endl;
            testFout<<flush;
        }
        testFout.seekp( 0, ios_base::beg );
        testFout<<"47414 47414 "<<iNumCounter<<endl<<endl;
        //for (int i = 0; i < 6; i++)
        //{
        //    testFout<<recoveryData[i]<<" ";
        //}
        //testFout<<endl;
        testFout.close();
        testFout.clear();
    }
  • 相关阅读:
    使用XE7并行库中的TTask(转)
    Delphi xe7并行编程快速入门(转)
    Pre-compile (pre-JIT) your assembly on the fly, or trigger JIT compilation ahead-of-time (转)
    使用RemObjects Pascal Script (转)
    Remobjects SDK 服务器搭建
    toString()方法
    环境变量
    jstl标签学习
    SQL的各种join
    Mybatis的一些配置
  • 原文地址:https://www.cnblogs.com/xiangwengao/p/2394139.html
Copyright © 2011-2022 走看看