c++ 文件操作

文本文件

c++中文件操作需要包含<fsream>

  • 操作文件的三大类

    ofstream; 写
    ifstream; 读
    fsteam; 读写
    

写文件

  1. 包含头文件
  2. 创建流对象
  3. 打开文件
  4. 写数据
  5. 关闭文件
#include <fstream>

void test01()
{
	ofstream ofs;
	ofs.open("test.txt", ios::out);

	ofs << "write some to test.txt" << endl;
	ofs.close();
}

int main()
{
	test01();
	return 0;
}

在这里插入图片描述

读文件

  1. 包含读文件
  2. 创建流对象
  3. 打开文件并判读是否打开成功
  4. 读数据
  5. 关闭文件
#include <fstream>

void test01()
{
	ifstream ifs;
	ifs.open("test.txt", ios::in);

	if (!ifs.is_open())
	{
		cout << "open file failed!" << endl;
		return;
	}

	//char buf[1024] = { 0 };
	//while (ifs >> buf)
	//{
	//	cout << buf << endl;
	//}
	//{

	//char buf[1024] = { 0 };
	//while (ifs.getline(buf, sizeof(buf)))
	//{
	//	cout << buf << endl;

	//}

	string buf;
	while (getline(ifs,buf))
	{
		cout << buf << endl;
	}

	//char c;
	//while ((c = ifs.get()) != EOF)
	//{
	//	cout << c;
	//}

}

int main()
{
	test01();
	return 0;
}

二进制文件

打开方式指定为 ios::binary

二进制写

#include <fstream>

class Person
{
public:
	char m_Name[64];
	int m_Age;
};

void test01()
{
	ofstream ofs;
	ofs.open("person.txt", ios::out | ios::binary);
	Person p = { "Tome", 18 };
	ofs.write((const char *) &p, sizeof (Person));
	ofs.close();
}


int main()
{
	test01();
	return 0;
}

二进制读

#include <fstream>

class Person
{
public:
	char m_Name[64];
	int m_Age;
};

void test01()
{
	ifstream ifs("person.txt", ios::in | ios::binary);
	
	if (!ifs.is_open())
	{
		cout << "file open failed!" << endl;
	}
	Person p;
	ifs.read((char*)&p, sizeof(Person));
	cout << p.m_Name << ":" << p.m_Age << endl;
	//cout << sizeof(Person) << endl;
    ifs.close();
}
int main()
{
	test01();
	return 0;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值