C++文件操作

简述:

C++文件操作也就是对文件流的操作,因而需要先引入包含文件流的头文件:<fstream>

然后C++该头文件提供了三种文件流,分别是fstream(文件流)、ifstream(输入文件流)、ofstream(输出文件流)        [此处的输入输出是对程序而言]

在此基础上,文件流还有几种打开方式,如下:

除此之外还有一种打开方式:

ios::binary    //以二进制方式打开

文件写入:

写入文件可用文件流:fstream、ofstream

//样例代码
#include <iostream>
#include <fstream>
using namespace std;

int main(int argc, char** argv) {
	ofstream ofs;
	ofs.open("E:\\桌面材料\\新建文件夹\\新建 文本文档.txt", ios::out);
	ofs<<"阿巴阿巴阿巴巴"<<endl;
	ofs<<"Hello World!"<<endl;
	ofs.close();
	return 0;
} 

文件读取:

读取相对于写入有着更多的实现方式

读取文件可用文件流:fstram、ifstream

第一种:

#include <iostream>
#include <fstream>
using namespace std;

int main(int argc, char** argv) {
	ifstream ifs;
	ifs.open("E:\\桌面材料\\新建文件夹\\新建 文本文档.txt", ios::in);
	if(!ifs.is_open()) {
		cout<<"error!";
	}else {
		char buf[1024] = {0};    //对字符数组进行初始化
		while(ifs >> buf) {
			cout<<buf<<endl;
		}
	}
	ifs.close();
	return 0;
}

第二种:

#include <iostream>
#include <fstream>
using namespace std;

int main(int argc, char** argv) {
	ifstream ifs;
	ifs.open("E:\\桌面材料\\新建文件夹\\新建 文本文档.txt", ios::in);
	if(!ifs.is_open()) {
		cout<<"error!"<<endl;
	} else {
		char buf[1024] = {0};
		while(ifs.getline(buf, sizeof(buf))) {
			cout<<buf<<endl;
		}
	}
	ifs.close();
	return 0;
}

第三种:

#include <iostream>
#include <fstream>
#include <string> 
using namespace std;

int main(int argc, char** argv) {
	ifstream ifs;
	ifs.open("E:\\桌面材料\\新建文件夹\\新建 文本文档.txt", ios::in);
	if(!ifs.is_open()) {
		cout<<"error!";
	}else {
		string buf;
		while(getline(ifs, buf)) {
			cout<<buf<<endl;
		}
	}
	ifs.close();
	return 0;
}

第四种:(不推荐)

#include <iostream>
#include <fstream>
using namespace std;

int main(int argc, char** argv) {
	ifstream ifs;
	ifs.open("E:\\桌面材料\\新建文件夹\\新建 文本文档.txt", ios::in);
	if(!ifs.is_open()) {
		cout<<"error!"<<endl;
	} else {
		char c;
		while((c = ifs.get()) != EOF) {
			cout<<c;
		}
	}
	ifs.close();
	return 0;
}

  • 11
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值