【c++】黑马·4 文件操作

/*作者:jennie
* 开始时间:2022年03月24日 23:04:08 星期四 
* 结束时间:2022年03月24日 23:10:16 星期四 (6)
* 课程名:黑马c++
* 知识单元:143 61 C++文件操作-文本文件-写文件
* 属性:例题
* 具体题目要求:
*
*/
#include<iostream>
#include<fstream>
using namespace std;

int main() {
	ofstream ofs;
	ofs.open("text.txt", ios::out);
	ofs << "hello world";
	ofs.close();
	return 0;
}
/*作者:jennie
* 开始时间:
* 结束时间:
* 课程名:黑马c++
* 知识单元:144 62 C++文件操作-文本文件-读文件
* 属性:例题
* 具体题目要求:
*<fstream> 1.对象 2.开(判) 3.写 4.关
*/
#include<iostream>
#include<string>
#include<fstream>
using namespace std;

int main() {
	ifstream ifs;
	ifs.open("text.txt", ios::in);
	if (!ifs.is_open()) {
		cout << "文件打开失败"<<endl;
		return 0;
	}
	char buf[1024];
	/*while (ifs>>buf)
	{
		cout << buf<<endl;
	}*/
	while (ifs.getline(buf,sizeof(ifs))&&buf[0]!='p')
	{
		cout << buf << endl;
	}
	int n1, n2;
	char c;
	while (ifs >>c>>n1>>n2)
	{
		cout << c << "  "<<n1+n2<<endl;
	}
	/*string buf;
	while (getline(ifs,buf))
	{
		cout << buf;
	}
	char c;
	while (ifs.get(c))
	{
		cout << c;
	}*/
	return 0;
}
/*作者:jennie
* 开始时间:2022年03月25日 00:00:10 星期五 
* 结束时间:2022年03月25日 00:10:15 星期五 
* 课程名:黑马c++
* 知识单元:145 63 C++文件操作-二进制文件-写文件
* 属性:例题
* 具体题目要求:
*write(const char*,sizeof) Person p={}  &p  
*/
#include<iostream>
#include<fstream>
using namespace std;
class People {
public:
	char m_Name[64];
	int m_Age;
};
int main() {
	ofstream ofs("text2.txt",ios::out|ios::binary);
	People p = { "张三",18 };
	ofs.write((const char*)&p, sizeof(p));
	ofs.close();
	return 0;
}
/*作者:jennie
* 开始时间:2022年03月25日 00:10:22 星期五 
* 结束时间:
* 课程名:黑马c++
* 知识单元:146 64 C++文件操作-二进制文件-读文件
* 属性:例题
* 具体题目要求:
*is_open  read(char*,sizeof)
*/
#include<iostream>
#include<fstream>

using namespace std;
class People {
public:
	char m_Name[64];
	int m_Age;
};
int main() {
	ifstream ifs("text2.txt", ios::in | ios::binary);
	if (!ifs.is_open())
	{
		cout << "文件打开失败";
	}
	People p = { "张三",18 };
	ifs.read((char*)&p, sizeof(p));
	cout << p.m_Name << p.m_Age;
	ifs.close();
	return 0;
}

猜你喜欢

转载自blog.csdn.net/weixin_51695846/article/details/125364442