C++文件流的写与读

C++文件流的写与读

1. 头文件  #include<fstream> 
2. 这是头文件包含的模板 对外接口 
定义了一个文件指针来指向文件流   FILE *__CLRCALL_PURE_OR_CDECL 
extern _CRTIMP2_PURE FILE *__CLRCALL_PURE_OR_CDECL _Fiopen(
	const char *,
	ios_base::openmode, int);
extern _CRTIMP2_PURE FILE *__CLRCALL_PURE_OR_CDECL _Fiopen(
	const wchar_t *,
	ios_base::openmode, int);

 #ifdef _NATIVE_WCHAR_T_DEFINED
extern _CRTIMP2_PURE FILE *__CLRCALL_PURE_OR_CDECL _Fiopen(
	const unsigned short *,
	ios_base::openmode, int);

接下来看看写入操作:

void DEMO() {
	fstream  file("./test.txt", ios::out);
	//或者也可以  file.open("./test.txt", ios::out):
	if (!file.is_open()) {
		cout << "打开文件失败" << endl;
		return;
	}
	//输入文件内 实际上是缓冲区输入
	file << "姓名: 猴子" << endl;
	file << "年龄: 16" << endl;
	file << "性别: 男" << endl;

	file.close();

}

接下来读入文件四种读法:

void DEMOFILE() {
	fstream  file("./test.txt", ios::in);
	if (!file.is_open()) {
		cout << "打开文件失败" << endl;
		return;
	}
	//接下四种读法:
	//第一种
	char buf[1024] = { 0 };
    while (file.getline(buf, sizeof(buf))) {
	cout << buf << endl;
	}
	//第二种
	string buf;
	while (getline(file,buf)) {
	cout << buf << endl;
	}
	//第三种
	char c;
	while ((c = file.get()) != EOF) {
    cout << c;
	}
	//第四种
	char buf[1024] = { 0 };
	while (file>>buf) {
		cout << buf ;
		cout << endl;
	}

	file.close();
}

推荐使用第二种读入方法。

欢迎小白组队刷题: 价位

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值