c++的文件读写

cpp 复制代码
#include<iostream>
#include<string>
//1:引入头文件
#include<fstream>
using namespace std;
//把程序中的信息输出到缓冲区,然后写到文件
void test01()
{
	//2:定义流对象
	ofstream ofs;
	//3:打开文件,以写的方式打开,如果没有文件,就创建
	ofs.open("test.txt", ios::out | ios::trunc);
	//4:判断是否打开成功
	if (!ofs.is_open())
	{
		cout << "打开失败" << endl;
	}
	//5:写信息
	ofs << "姓名:灰灰" << endl;;
	ofs << "年龄:20" << endl;
	//6:关闭文件
	ofs.close();//关闭文件,并刷新缓冲区
}
//把磁盘信息输入到缓冲区,然后读到程序中(读文件)
void test02()
{
	ifstream ifs;
	ifs.open("test.txt", ios::in);
	if (!ifs.is_open())
	{
		cout << "打开失败" << endl;
	}
	//第一种方式读取文件
	//一行一行读
	/*char buf[1024] = { 0 };
	while (ifs >> buf)
	{
		cout << buf << endl;
	}*/
	//第二种方式读取文件
	//char buf[1024] = { 0 };
	//while (!ifs.eof())//判断是否读到文件尾部
	//{
	//	ifs.getline(buf, sizeof(buf));
	//	cout << buf << endl;
	//}
	//第三种方式,一个一个字符读
	char c;
	while ((c = ifs.get()) != EOF)
	{
		cout << c;
	}
	ifs.close();
}

int main()
{
	test02();
	system("pause");
	return EXIT_SUCCESS;
}

c++的二进制读写

cpp 复制代码
using namespace std;
class maker
{
public:
	maker()
	{

	}
	maker( const char*name,int age)
	{
		strcpy(this->name, name);
		this->age = age;


	}
	
public:
	int age;
	char name[64];
};
void test()
{
	maker m1("huihi", 20);
	maker m2("huifa",2);
	ofstream ofs;
	ofs.open("text.txt", ios::out |ios::trunc| ios::binary);
	if (!ofs.is_open())
	{
		cout << "打开失败" << endl;
	}
	//写
	ofs.write((const char*)&m1, sizeof(maker));
	ofs.write((const char*)&m2, sizeof(maker));
	ofs.close();
}
//读
void test02()
{
	ifstream ifs;
	ifs.open("text.txt", ios::in | ios::binary);
	if (!ifs.is_open())
	{
		cout << "打开失败" << endl;
	}
	//读
	maker m1;
	maker m2;
	ifs.read((char*) & m1, sizeof(maker));
	ifs.read((char*)&m2, sizeof(maker));
	cout << "name:" << m1.name << "age:" << m1.age << endl;
	cout << "name:" << m2.name << "age:" << m2.age << endl;
}
int main()
{
	test02();
	system("pause");
	return EXIT_SUCCESS;
}
相关推荐
ftpeak几秒前
网络爬虫Playwright Python 教程:从入门到实战
开发语言·爬虫·python·playwright
摸鱼界在逃劳模3 分钟前
Java的JDK下载与安装
java·开发语言
qq_120840937112 分钟前
Three.js 骨骼动画工程实战:AnimationMixer、剪辑与混合权重调参
开发语言·javascript·ecmascript
zandy101113 分钟前
衡石科技|HENGSHI CLI登场,以Rust架构驱动BI自动驾驶
开发语言·科技·rust
沐知全栈开发17 分钟前
jEasyUI 合并单元格详解
开发语言
沛沛rh4524 分钟前
用 Rust 实现用户态调试器:mini-debugger项目原理剖析与工程复盘
开发语言·c++·后端·架构·rust·系统架构
范什么特西30 分钟前
解决idea未指定jdk问题webapp未被识别问题
java·开发语言·intellij-idea
云栖梦泽32 分钟前
Linux内核与驱动:13.从设备树到Platform平台总线
linux·运维·c++·嵌入式硬件
qeen8736 分钟前
【算法笔记】模拟与高精度加减乘除
c++·笔记·算法·高精度·模拟
txinyu的博客39 分钟前
高并发内存池 - 简化版 tcmalloc
c++