记录:c++读写文件操作

1.初步使用写文件
在C++中对文件进行操作必须包含头文件。
对文件操作的类:
fstream:可读可写操作
ifstream:只能读操作
ofstream:只能写操作
简单案例:

#include<iostream>
#include<fstream>//包含头文件
using namespace std;
int main()
{
	ofstream fd;//创建流对象
	fd.open("zby.txt");//打开文件
	fd<< "aaaaaaaaaaa";
	fd.close();//关闭文件
	return 0;
}

2.打开方式
文件的打开方式:
ios::in 为读文件打开方式
ios::out 为写文件打开方式
ios::ate 初始位置文件尾
ios::app 写文件尾追加
ios::trunc 若文件存在先删除,在创建
ios::binary 二进制方式打开

#include<iostream>
#include<fstream>//包含头文件
using namespace std;
int main()
{
	ofstream fd;//创建流对象
	fd.open("zby.txt",ios::app);//打开文件如果没有会自动创建,
	//fd.open("zby.txt", ios::in|ios::out|ios::trunc )//可读可写可创建
	fd<< "aaaaaaaaa";
	fd<< "bbbbbbbbbbb";//追加在上一行后面
	fd.close();//关闭文件
	return 0;
}

3读文件
案例1:

#include<iostream>
#include<fstream>//包含头文件
using namespace std;
int main()
{
	ifstream fd("zby.txt", ios::in);
	if (!fd.is_open()){
		cout << "文件不存在" << endl;
	}
	char arr[1024] = { 0 };
	while (fd >> arr){
		cout << arr << endl;
	}
	fd.close();
	return 0;
}

案例2:

#include<iostream>
#include<fstream>//包含头文件
using namespace std;
int main()
{
	ifstream fd("zby.txt", ios::in);
	if (!fd.is_open()){
		cout << "文件不存在" << endl;
	}
	char arr[1024] = { 0 };
	while (fd.getline(arr, sizeof(arr))){//按行读取
		cout << arr << endl;
	}
	fd.close();
	return 0;
}

案例3:

#include<iostream>
#include<string>
#include<fstream>//包含头文件
using namespace std;
int main()
{
	ifstream fd("zby.txt", ios::in);
	if (!fd.is_open()){
		cout << "文件不存在" << endl;
	}
	string arr;
	while (getline(fd, arr)){
		cout << arr << endl;
	}
	fd.close();
	return 0;
}

END.

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值