c++编写打开文件进行读写的函数

/*
编写打开文件用于输入输出的函数
*/
#include <iostream>
#include <string>
#include <fstream>

using namespace std;

//编写open_in_file函数打开文件用于输入
ifstream& open_in_file(ifstream &in,const string &file)
{//利用引用传递可以改变实参,string类型利用const的引用不改变实参,提高效率
	//in为ifstream流对象
	//防止该流已经打开,所以在打开文件前关闭该流对象
	in.close();
	//清空流对象
	in.clear();
	in.open(file.c_str(),ifstream::in);
	return in;
}
//编写函数open_file1打开文件用于输出
ofstream& open_out_file(ofstream &out,const string &file)
{
	out.close();
	out.clear();
	out.open(file.c_str(),ofstream::out | ofstream::app);
    return out;
}
int main()
{
	ifstream infile;
	open_in_file(infile,"map_file.txt");
	if(!infile)
	{
		//报错
	}
	else
	{
		string s;
		while(!infile.eof())
		{
		  getline(infile,s);
		  cout << s << endl;
		}
		infile.close();
	}
	ofstream outfile;
	if(!outfile)
	{
		//报错
	}
	else
	{
		open_out_file(outfile,"map_file.txt");
	    outfile << "111    2222" <<endl;
	}
	outfile.close();
	return 0;
}

在应用中,我们常常都要打开给定的文件用于输入和输出,所以在此我把两个常用的函数写出来,供大家参考。


  • 0
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值