C++文件输入输出

文件输入输出,可用于参数的传入,结果的输出

共包含五步

1.包含头文件

2.创建流对象

3.打开文件   流对象.open(文件名 ,  打开方式) 

4.写/读   <<  getline()   write()  read()

5.关闭文件  流对象.close

#include<iostream>
//包含头文件
#include<fstream>
#include<string>
using namespace std;
void test_write();
void test_read();

void binarytest_write();
void binarytest_read();
int main() {
	//test_write();
	//test_read();
	
	//binarytest_write();
    binarytest_read();
	return 0;
}

void test_write()
{

	ofstream ofs;

	//打开方式,out:代表为写文件而打开
	ofs.open("text.txt",ios::out);
	//写文件
	ofs << "姓名:张三" << endl;
	ofs << "姓别:男" << endl;
	ofs << "年龄:18" << endl;
	//关闭文件
	ofs.close();
}

void test_read()
{
	//创建流对象
	ifstream ifs;

	//打开
	ifs.open("text.txt", ios::in);
	if (!ifs.is_open())
	{
		cout << "file opens 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 f;
	//逐字符读取
	//while ((f = ifs.get()) != EOF)
	//{
	//	cout << f;
	//}

	//关闭文件
	ifs.close();
}

class Person
{
public:
	char m_name[64];
	int m_age;
};

void binarytest_write()
{
	//创建输出流对象
	ofstream ofs;
	//打开文件,二进制方式写
	ofs.open("person.txt",ofs.out| ofs.binary);
	//写文件
	Person p = { "张三", 18 };
	ofs.write((const char*)&p,sizeof(p));
	//关闭文件
	ofs.close();
}

void binarytest_read()
{
	//创建输入流对象
	ifstream ifs;
	//打开文件,二进制方式读
	ifs.open("person.txt", ifs.in | ifs.binary);
	if(!ifs.is_open())
	{
		cout << "file opens failed" << endl;
		return;
	}
	Person p;
	ifs.read((char*)&p,sizeof(p));
	cout << "姓名:" << p.m_name << endl;
	cout<<"年龄:" << p.m_age << endl;
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值