您的位置:首页 > 其它

076day(文件读写和题目练习)

2017-12-26 00:49 225 查看
172210704111-陈国佳总结《2017年12月26日》【连续076天】

标题:文件读写和题目练习;

内容:A.练习了一道PAT题,一开始超时了,优化后,又发生了段错误,明天再优化;

B.文件读写:

#include<fstream>

ofstream outFile("clients.dat",ios::out|ios::binary);

-clients.dat 创建文件名

-ios::out 文件打开方式(ios::out)输出到文件,删除原有内容;(ios::app)保留原有内容,在尾部添加;

-ios::binary 以二进制格式打开文件;

1.创建文件:

先创建ofstream对象,在open函数打开:

ofstream fout;  fout.open("test.out",ios::out|ios::binary);

判断打开是否成功:

if(!fout){cout<<"File open error!"<<endl;}

文件名可以给出绝对路径,也可以给相对路径;没交代,就是在当前文件夹下找文件;

2.文件的读写指针:

对于输入输出文件,有一个读写指针;

ifstream fin("a1.in',ios::ate);

long location=fin.tellg();   //取得指针位置;

fin.seekg(location,/ios::beg/ios::cur/ios::end);  将指针读到第l个字节处//从头数location//从当前位置数L//从尾部数L;

L可为负值;

显示关闭文件:

ifstream fin("test.dat",ios::in);

fin.close();

ofstream fout("test.dat",ios::out);

fout.close();

#include<iostream>
#include<fstream>
#include<vector>
#include<algorithm>
using namespace std;
int main()
{ vector<int> v;
ifstream srcFile("in.txt",ios::in);
ofstream destFile("out.txt",ios::out);
int x;
while(srcFile>>x)
v.push_back(x);
sort(v.begin(),v.end());
for(int i=0;i<v.size();i++)
destFile<<v[i]<<" ";
destFile.close();
srcFile.close();
return 0;
} in.txt:1 234 9 45 6 879

运行后,出现out.txt:1 6 9 45 234 879 

明日计划:复习;
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: