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
在执行的时候,发现数据没有用空格分开,可以在写入数据之前,先写入一个空格。
一些总结,希望对你有所帮助。
- [C/C++]文件操作
- 文件操作--C 函数操作
- c文件操作
- C文件操作
- C的文件操作
- c语言文件操作
- C的文件操作
- 标准C文件操作
- C#文件操作
- C的文件操作
- C语言文件操作
- C语言文件操作
- C文件操作探索
- [C++]文件读写操作
- C/C++文件操作
- C文件操作
- C语言文件操作
- c文件操作
- Java程序员到架构师的推荐阅读书籍
- itext 生成pdf文档
- android异步下载网络图片(二)
- LeetCode88——Merge Sorted Array
- tomkeeper 的DEP/ASLR bypass without ROP/JIT
- C++ 文件操作
- android从相册选取与拍照上传最终解决版
- javascript 判读字符串是否为数字
- 进程
- Java 内部类
- 冰冻三尺非一日之寒之产品观
- Android动画初探
- 介绍EF提供的3中查询方式
- java.util.Scanner.close()方法