65.C++文件读写

写文件
ofstream  ofs
open 指定打开方式
isopen 判断是否打开成功
ofs << “数据”
ofs.close
读操作
ifstream  ifs
指定打开方式 ios::in
isopen判断是否打开成功
三种方式读取数据

#define _CRT_SECURE_NO_WARNINGS
#include<iostream>
using namespace std;
//文件读写头文件
#include <fstream>

//写文件
void test01()
{
	//以输出的方式打开文件
	//ofstream ofs("./test.txt", ios::out | ios::trunc);
	//后期指定打开方式
	
	ofstream ofs;
	ofs.open("./test.txt", ios::out | ios::trunc);
	//判断是否打开成功
	if ( !ofs.is_open())
	{
		cout << "打开失败" << endl;
	}

	ofs << "姓名:abc" << endl;
	ofs << "年龄:100" << endl;
	ofs << "性别:男" << endl;


	ofs.close();

}

//读文件
void test02()
{
	ifstream ifs;
	ifs.open("./test.txt", ios::in);

	//判断是否打开成功
	if (!ifs.is_open())
	{
		cout << "打开失败" << endl;
	}

	//第一种方式
	//char buf[1024];

	//while (ifs >>buf) //按行读取
	//{
	//	cout << buf << endl;
	//}

	//第二种方式
	//char buf2[1024];

	//while (!ifs.eof()) //eof读到文件尾
	//{
	//	ifs.getline(buf2, sizeof(buf2));
	//	cout << buf2 << endl;
	//}

	//第三种 不推荐 按单个字符读取
	char c;
	while (  (c = ifs.get() ) != EOF) // EOF文件尾
	{
		cout << c;
	}

	ifs.close();

}



int main(){
	//test01();
	test02();

	system("pause");
	return EXIT_SUCCESS;
}


 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值