c++基础-补漏日记6(读写+二进制读写)

目录

写文件

读文件

二进制写文件 

二进制读文件 

读取文件中的数字

缺点


写文件

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

void test() {
	ofstream ofs;										//创建流对象
	ofs.open("新建文本文档.txt", ios::out);				//打开文件,选择打开方式(ios::out为写文件 方式)

	ofs << "清明时节雨纷纷,路上行人欲断魂" << endl;	//写入
	ofs << "借问酒家何处有,牧童遥指杏花村" << endl;	//写入

	ofs.close();										//关闭
}

int main() {
	test();
}

(若没有先创建文档,会在cpp文件夹下自动创建) 

读文件

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

void test() {
	ifstream ifs;								//创建流对象
	ifs.open("新建文本文档.txt", ios::out);		//打开文件,选择打开方式

	if (!ifs.is_open()) {						//判断是否存在该文件等
		cout << "文件打开失败" << endl;
		return;
	}
	//读数据方式

	/*
	//第一种
	char buf[1024] = { 0 };
	while (ifs>>buf) {		        
		cout << buf << endl;
	}
	//第二种
	char buf1[1024] = { 0 };
	while (ifs.getline(buf1,sizeof(buf1))) {		
		cout << buf1 << endl;
	}
	*/

	//第三种
	string buf2;
	while (getline(ifs, buf2)) {
		cout << buf2 << endl;
	}
	ifs.close();								//关闭
}

int main() {
	test();
}

二进制写文件 

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

class student {
public:
	student(int a) {
		age = a;
	}
	int age;
};
void test() {
	//第一步
	/*ofstream ofs;
	ofs.open("新建文本文档.txt", ios::out | ios::binary);*/
							//↓合并↓//
	ofstream ofs("新建文本文档.txt", ios::out | ios::binary);//  写文件 | 二进制方式
	

	//第二步
	student stu(18);
	ofs.write((const char *)&stu,sizeof(student));

	//第三步
	ofs.close();
}

int main() {
	test();
}

二进制读文件 

(读取上条存好的二进制数据)

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

class student {
public:
	student() {};
	student(int a) {
		age = a;
	}
	int age;
};
void test() {
	//第一步 创建一个输入流对象(?)
	ifstream ifs("新建文本文档.txt",ios::in|ios::binary );
	if (!ifs.is_open())
	{
		cout << "打开失败" << endl;
		return;
	}

	//第二步 读对象
	student stu;
	ifs.read((char*)&stu,sizeof(student));//将二进制文件的东西赋予给对象
	cout << "学生年龄::" << stu.age << endl;

	//第三步 关闭文件
	ifs.close();

}

int main() {
	test();
}

 out:我的输出出去

 in:东西输入进来,让我打印

 创建流对象和open操作可合并

  打开操作加这个严谨一点

 if (!ifs.is_open())
    {
        cout << "打开失败" << endl;
        return;
    } 

检测是否为空

    char ch;
    ifs >> ch;//往右读一个字符
    if (ifs.eof()) {//监测文件是否为空
        cout << "文件为空" << endl;
        return;
    } 

读取文件中的数字

挺神奇,遇到整型进入循环,没遇到整型也不会跳出循环。直到遇到终止符。

ifs将读到的整型暂存与a? ↓

 

缺点:

读到一个整型+1。但一旦读到不是整型的,就会跳出循坏,从而读不到后面

改进:暂时想不到

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值