c++文件操作基础

需要包含头文件<fstream>

一、文本文件

配合使用时,可以用 |  ,即ios::binary | ios::out

#include<bits/stdc++.h>
#include<fstream>
using namespace std;

int main() {
	ofstream ofs;
	ofs.open("testfiles.txt", ios::out);		//往文件中写入内容
	ofs << "123 123" << endl;
	ofs << "456 456" << endl;
	ofs.close();


	//读取文件:
	ifstream ifs;
	ifs.open("testfiles.txt", ios::in);
	if (!ifs.is_open()) {
		cout << "Error!" << endl;
		return 0;
	}
	//四种读取文件数据的方法
	//1.
	//char buf[10000] = { 0 };	
	//while (ifs >> buf) {
	//	cout << buf << endl;
	//}

	//2.
	char buf[10000] = { 0 };
	while (ifs.getline(buf, sizeof(buf))) {		//两个参数,一个是指针,一个是读取的字节数
		cout << buf << endl;			//不能自动读取行末尾的回车符,要手动endl
	}

	//3.
	string buf;
	while (getline(ifs,buf)) {		//不能自动读取行末尾的回车符,要手动endl
		cout << buf << endl;
	}

	//4.
	char c;
	while ((c = ifs.get()) != EOF) {
		cout << c;
	}

	ifs.close();
	return 0;
}

二、二进制文件

打开方式要指定为ios::binary

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

//二进制可以自定义写入的数据类型
class Person {
public:
	int mAge;
	char mName[10];
	Person() {

	}
	Person(int age, const char name[]) {	//这边要加个const防止出问题
		this->mAge = age;
		strcpy_s(mName,name);
	}
};

int main() {

	//文件写入操作
	ofstream ofs("textbinary.txt", ios::out | ios::binary);
	Person p(18, "cpx");
	ofs.write((const char*)&p, sizeof(Person));		//注意这边写法
	ofs.close();

	//读文件操作
	ifstream ifs("textbinary.txt", ios::in | ios::binary);
	if (!ifs.is_open()) {
		cout << "Error!" << endl;
		return 0;
	}
	Person p2;
	ifs.read((char*)&p2, sizeof(Person));			//注意这边写法
	cout << p2.mName << " " << p2.mAge << endl;
	ifs.close();

	return 0;
}

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值