实验六、文件输出流对象,写入若干行文字,关闭文件输出流对象,然后观察磁盘文件内容

1.通过文件输出流对象,写入若干行文字;

2.关闭文件输出流对象,然后观察磁盘文件内容;

3.改用open函数创建文件输出流,并选择适当的文件操作方式;

4.在原内容的后面追加若干行新内容;

基本要求:能熟练运用文件各种操作编写程序测试并提交程序。

#include<iostream>
#include<fstream>//文件操作头文件
#include<string>
using namespace std;
void test01()
{
	//2.创建流对象
	ofstream ofs;
	//3.打开文件
	ofs.open("test.txt", ios::out);
	//4.写数据
	ofs << "姓名:路明非" << endl;
	ofs << "年龄:18" << endl;
	ofs << "性别:未知" << endl;
	ofs << "籍贯:龙族" << endl;
	//5.关闭文件
	ofs.close();
}
int main()
{
	test01();
	system("pause");
	return 0;
}

text文件写入 姓名  年龄  性别  籍贯信息: 

 

#include<iostream>
#include<fstream>
using namespace std;
int main()
{
	ofstream ofs;
	ofs.open("test.txt", ios::out | ios::app);
	ofs << "学校:XXX" << endl;
	ofs << "婚配:XXX" << endl;
	ofs.close();
	system("pause");
	return 0;
}

结果:在后面添加  学校  婚配  信息: 

#include<iostream>
#include<fstream>
#include<string>
using namespace std;
int main()
{
	ifstream ifs;
	ifs.open("test.txt", ios::in);
	if (!ifs.is_open())//判断是否打开
	{
		cout << "打开失败" << endl;
		return 0;
	}
	string buf;//读文件
		while (getline(ifs, buf))
		{
			cout << buf << endl;
		}
	ifs.close();
	system("pause");
	return 0;
}

运行查看结果: 

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值