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;
}
相关推荐
程子的小段21 分钟前
C 语言实例 - 字符串复制
c语言·开发语言
-森屿安年-40 分钟前
STL 容器:stack
开发语言·c++
歪歪10042 分钟前
C#如何在数据可视化工具中进行数据筛选?
开发语言·前端·信息可视化·前端框架·c#·visual studio
charlee441 小时前
最小二乘问题详解6:梯度下降法
c++·梯度下降·雅可比矩阵·非线性最小二乘·参数拟合
房开民1 小时前
OpenCV C++ 中,访问图像像素三种常用方法
c++·opencv·计算机视觉
报错小能手2 小时前
C++笔记(面向对象)深赋值 浅赋值
c++·笔记·学习
Jyywww1212 小时前
Python基于实战练习的知识点回顾
开发语言·python
Tony Bai2 小时前
【Go 网络编程全解】14 QUIC 与 HTTP/3:探索下一代互联网协议
开发语言·网络·后端·http·golang
爱吃小胖橘2 小时前
高效对象池设计:提升Unity性能的关键
开发语言·unity·c#·游戏引擎
是苏浙2 小时前
零基础入门C语言之深入了解指针2
c语言·开发语言