Essential C++ 1.7文件的读写

本文深入探讨了C++中的文件读写操作,包括打开、读取、写入和关闭文件的基本方法,以及如何处理文件流和错误处理策略。通过实例代码,读者将掌握高效管理文件内容的关键技巧。
摘要由CSDN通过智能技术生成

#include <fstream> //头文件

//以输出模式打开 hello.txt

ofstream outfile("hello.txt");

//以追加模式 ( append mode ) 开启hello.txt

//要提供第二个参数 ios_base::app 传给ostream对象

//新数据会被加到文件尾端

ofstream outfile("hello.txt", ios_base::app);

//如果 outfile 的计算结果为 false, 表示此文件未开启成功

if (!outfile){

	//因为某种原因,文件无法开启

	cerr << "Oops! Unable to save session data!\n";
}

else{

	//ok: outfile 开启成功,接下来将数据写入

	outfile << name << " " << id << " " << sex << " " << addr << endl;
}

//以读取模式 ( input mode ) 开启 infile

ifstream infile("hello.txt");

if (!infile) {

	//由于某种原因,文件无法开启……

}

else {

	while (infile >> name) {

		infile >> id >> sex >> addr;

		if (name == find_name) {

			//找到他了

			cout << name << " " << id << " " << sex << " " << addr << endl;

		}

	}

}

//如果想要同时读写同一个文件,得定义一个fstream对象
//为了以追加模式(append mode)开启,我们得传入第二参数值ios_base::in | ios_base::app
fstream iofile("hello.txt", ios_base::in | ios_base::app);
if (!iofile)
	//由于某种原因,文件无法开启
else{
	//开始读取之前,将文件重新定位至起始处
	//以附加模式开启文件时,文件位置会位于尾端,没有重新定位则会遇到eof
	iofile.seekg(0);
}

通过 fstream 的 close 函数来关闭文件, inflie.close()  outfile.close()   iofile.close()


#include <iostream>
#include <string>
#include <fstream>
using namespace std;
struct Person{
	string name;
	long long id;
	char sex;
	string addr;
};
int main()
{
	Person per;
	char ch = 'y';
	//outfile
	ofstream outfile("fuck.txt");
	while (ch != 'n'){
		cout << "输入姓名 学号 性别 地址: ";
		cin >> per.name >> per.id >> per.sex >> per.addr;
		outfile << per.name << " " << per.id << " " << per.sex << " " << per.addr << endl;
		cout << "继续输入?(y or n): ";
		cin >> ch;
	}
	outfile.close();
	//infile
	ifstream infile("fuck.txt");
	while (!infile.eof()){
		infile >> per.name >> per.id >> per.sex >> per.addr;
		cout << per.name << " " << per.id << " " << per.sex << " " << per.addr << endl;
	}
	infile.close();
	system("pause");
	return 0;
}











评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值