《Essential C++》系列笔记之第一章(C++编程基础)之第七节(文件的读写)

在这里插入图片描述
代码实践:

#include <iostream>
using namespace std;
#include <fstream>
#include <string>

int main()
{
	//文件写出操作
#if 0
	//ofstream OutFile("hmj.txt"); //如果文件之前没有就会创建,有就会覆盖

	ofstream OutFile("hmj.txt", ios_base::app); //如果文件之前没有就会创建,有就追加而不覆盖

	if (!OutFile)
	{
		cerr << "打开失败!" << endl;
	}
	else
	{
		OutFile << "hehe" << " " << 1 << " "  << 2 << endl;
	}
#endif

	//文件读入操作
#if 0
	ifstream InFile("hmj.txt");
	if (!InFile)
	{
		cerr << "此文件不存在" << endl;
	}
	else
	{
		string s1;
		int a = 0, b = 0;
		while (InFile >> s1 >> a >> b)
		{
			
			cout << s1 << " " << a << " " << b << endl;
		}
	}
#endif

	//文件读写操作
#if 0
	fstream IOFile("hmj.txt", ios_base::app | ios_base::in); //这里少加了ios_base::in会导致后面读操作失败 但是少了ios_base::out写操作没有影响

	if (!IOFile)
	{
		cerr << "打开失败" << endl;
	}
	else
	{
		//先写(app方式)
		IOFile << "hmj" << " " << 1 << " " << 2 << endl;

		//再读
		IOFile.seekg(0);
		string s;
		int b = 0, c = 0;
		while (IOFile >> s >> b >> c)
		{
			cout << s << " " << b << " " << c << endl;
		}
	}
#endif


	system("pause");
	return 0;
}

今天是20200227 《数据结构与算法图解》我来啦😍!

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值