C++文件操作

简述:

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

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

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

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

cpp 复制代码
ios::binary    //以二进制方式打开

文件写入:

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

cpp 复制代码
//样例代码
#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

第一种:

cpp 复制代码
#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;
}

第二种:

cpp 复制代码
#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;
}

第三种:

cpp 复制代码
#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;
}

第四种:(不推荐)

cpp 复制代码
#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;
}
相关推荐
zc.ovo1 分钟前
图论水题4
c++·算法·图论
诗书画唱12 分钟前
【前端面试题】JavaScript 核心知识点解析(第二十二题到第六十一题)
开发语言·前端·javascript
冬天vs不冷13 分钟前
Java基础(九):Object核心类深度剖析
java·开发语言·python
TS的美梦14 分钟前
【1:1复刻R版】python版火山图函数一键出图
开发语言·python·r语言·scanpy·火山图
眠りたいです1 小时前
Qt音频播放器项目实践:文件过滤、元数据提取与动态歌词显示实现
c++·qt·ui·音视频·媒体·qt5·mime
陈天伟教授1 小时前
(二)Python + 地球信息科学与技术 (GeoICT)=?
开发语言·python
汤永红1 小时前
week2-[循环嵌套]数位和为m倍数的数
c++·算法·信睡奥赛
1白天的黑夜14 小时前
前缀和-560.和为k的子数组-力扣(LeetCode)
c++·leetcode·前缀和
七七&55610 小时前
2024年08月13日 Go生态洞察:Go 1.23 发布与全面深度解读
开发语言·网络·golang
java坤坤10 小时前
GoLand 项目从 0 到 1:第八天 ——GORM 命名策略陷阱与 Go 项目启动慢问题攻坚
开发语言·后端·golang