五、c++简单的文件操作

一、基本操作

1.定义输入文件:

ifstream ifile;

定义输出文件:

ofstream ofile;

2.打开文件:

ifile.open("这里是路径比如d:\\test.txt");

ofile.open("路径");

3.对文件内容读写:就用>> << getline get就可以,cin用ifile代替,cout用ofile代替

4.关闭文件:

ifile.close(); ofile.close();

举个例子:写入一下话进文件

#include <fstream>//注意头文件

using namespace std;

int main()
{
  ofstream ofile;
  ofile.open("myfile.txt");
  ofile<<"这是一个测试的文本"<<endl;
  for(int i=0;i<100;i++){
    ofile<<i<<endl;
  }
  ofile.close();
    return 0;
}

这时如果有这个名字的就在里面改,没有就新建了,而且每次执行文件内容是刷新,不是在后头追加。

在来一个读的例子:要是没有我路径指定的文件,就输出空了

#include <fstream>//注意头文件
#include <iostream>
using namespace std;

int main()
{
    char ch[255];
  ifstream ifile;
  ifile.open("myfile.txt");
  ifile.getline(ch,255);
  cout<<ch<<endl;
  ifile.close();
    return 0;
}



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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值