C++ 文件操作

来源:互联网 发布:淘宝砍价师靠谱吗 编辑:程序博客网 时间:2024/06/08 10:42

代码:

ngnsvr9 [** NONE **]/home/xionghailong/c++/file/local_file $ cat local.cpp
#include <fstream>
#include <iostream>
#include <vector>

using namespace std;

int main()
{
        //同时可以读写
        fstream file ("score.txt", ios::in | ios::out);
        if( !file.is_open() )//判断是否打开
        {
                cout<<"could not open file"<<'\n';
                return 0;
        }
        //读入当前数据
        int new_score;
        cout<<"please input a new score:  ";
        cin>>new_score;

        //获取当前位置
        streampos pre_score_pos = file.tellg();

        //采用循环找到比new_score小的数值位置
        int cur_score;
        while( file >> cur_score )
        {
                if ( cur_score < new_score )
                {
                        break;
                }
                pre_score_pos =file.tellg();
        }

        //检查读入是否有问题
        if ( file.fail() && !file.eof() )
        {
                cout<<"bad score or read exit"<<'\n';
                return 0;
        }
        file.clear();

        //回到想要插入的位置
        file.seekg( pre_score_pos );

        //读取输入数据
        vector<int>  scores;
        while ( file >> cur_score )
        {
                scores.push_back( cur_score );
        }

        if( !file.eof() )
        {
                cout<<"bad score or read exit"<<'\n';
                return 0;
        }

        file.clear();

        file.seekp( pre_score_pos );

        //if ( !(pre_score_pos == 0 ) )
        //{
                //file << endl;
        //}

        file << new_score <<endl;

        for ( vector<int>::iterator it = scores.begin(); it != scores.end(); ++it)
        {
                file << *it <<endl;
        }
}

ngnsvr9 [** NONE **]/home/xionghailong/c++/file/local_file $ cat score.txt
88 89 78 65 64 50 45 30

编译执行:

ngnsvr9 [** NONE **]/home/xionghailong/c++/file/local_file $ g++ local.cpp
ngnsvr9 [** NONE **]/home/xionghailong/c++/file/local_file $ ./a.out
please input a new score:  6
ngnsvr9 [** NONE **]/home/xionghailong/c++/file/local_file $ ./a.out
please input a new score:  8
ngnsvr9 [** NONE **]/home/xionghailong/c++/file/local_file $ cat score.txt
88 89 78 65 64 50 45 3068

在执行的时候,发现数据没有用空格分开,可以在写入数据之前,先写入一个空格。

 

一些总结,希望对你有所帮助。

0 0
原创粉丝点击