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

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 


明日计划:复习;

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值