我的C++之旅---06

我的C++之旅—06

(原创)
很基础的文件和二进制文件的读写问题。

功能:基础的文件的读写

代码如下:

#include<iostream>
#include<fstream>
#include<stdio.h>
#include<string>
using namespace std;

class Person {
public:
	string name;
	int age;
}p;

void test01write() {
	ofstream ofs;
	ofs.open("test.txt", ios::out);
	ofs << "真牛比" << endl;
	ofs.close();
}

void test02read() {
	ifstream ifs;
	ifs.open("test.txt", ios::in);
	if (!ifs.is_open()) {
		cout << "文件打开失败" << endl;
	}
	
	
	//读取数据方法1
	char buf[1024] = { 0 };
	while (ifs >> buf) {
		cout << buf << endl;
	}
	//读取数据方法2
	char bf[1024] = { 0 };
	while (ifs.getline(buf, sizeof(buf))) {
		cout << bf << endl;
	}
	//读取数据方法3
	string bg;
	while (getline(ifs, bg)) {
		cout << bg << endl;
	}
	//读取数据方法4
	char c;
	while ((c = ifs.get()) != EOF) {
		cout << c;
	}

	ifs.close();
}

void test03write() {
	ofstream ofss;
	ofss.open("person.txt", ios::out | ios::binary);
	p = { "zhangsan",18 };
	ofss.write((const char *)&p,sizeof(Person));
	ofss.close();
}

void test04read() {
	ifstream ifss;
	ifss.open("person.txt", ios::in | ios::binary);
	ifss.read((char*)&p, sizeof(Person));
	cout << p.name << p.age << endl;
	ifss.close();
}

int main() {
	int i, n, m;
	test01write();
	test02read();
	test03write();
	test04read();
	system("pause");
	return 0;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值