C++学习笔记_006_文件操作

为什么要进行文件操作:
程序运行时产生的数据属于临时数据,程序一旦运行结束后都会被释放。通过文件可以将数据持久化,操作文件需要include <fstream>。

操作文件的三大类:ofstream(写操作)  ifstream(读操作)  fstream(读写操作)

 示例1,读写文本文件:

#include <iostream>
#include <string>
#include <fstream> // 包含头文件 fstream
using namespace std;

// 写文件
void test01() {
	// 创建流对象
	ofstream ofs;
	// 指定打开方式
	ofs.open("test.txt", ios::out);
	// 写内容
	ofs << "姓名:张三" << endl;
	ofs << "姓别:男" << endl;
	ofs << "年龄:18" << endl;
}

// 读文件
void test02() {
	// 创建流对象
	ifstream ifs;
	// 打开文件并判断是否成功
	ifs.open("test.txt", ios::in);
	// 读内容
	if (!ifs.is_open()) {
		cout << "open file fail" << endl;
		return; 
	}
	//方法一
	/*char buf[1024] = { 0 }; 
	while (ifs >> buf) {
		cout << buf << endl; 
	}*/
	//方法二
	/*char buf[1024] = {};
	while (ifs.getline(buf, sizeof(buf))) {
		cout << buf << endl; 
	}*/
	//方法三
	string buf;
	while (getline(ifs, buf)) {
		cout << buf << endl; 
	}
	//方法四
	/*char c; 
	while ((c=ifs.get()) != EOF) {
		cout << c;
	}*/
}

int main() {
	//test01();
	test02();
	return 0; 
}

示例2,读写二进制文件:

#include <iostream>
#include <string>
#include <fstream> // 包含头文件 fstream
using namespace std;

class person {
public:
	char m_name[64];
	int m_age;
};

void test01() {
	ofstream ofs;
	// 打开文件
	ofs.open("person.txt", ios::out | ios::binary);
	// 写文件
	person p = { "张三", 18 };
	ofs.write((const char*)&p, sizeof(person));
}

void test02() {
	ifstream ifs;
	ifs.open("person.txt", ios::in | ios::binary);
	if (!ifs.is_open()) {
		cout << "fail to open" << endl;
		return;
	}
	person p;
	ifs.read((char*)&p, sizeof(person));
	cout << "姓名:" << p.m_name << " 年龄: " << p.m_age << endl;
	ifs.close();
}

int main() {
	test01();
	test02();
	return 0; 
}

感觉这里黑马讲的太糙了,实际运用的时候需要再查更细节的操作。

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值