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;
}
相关推荐
Augustzero11 小时前
为什么线程不能说睡就睡?看懂等待与唤醒机制
c++·后端
程序员与背包客_CoderZ12 小时前
Linux D-Bus通信协议详解:从入门到C/C++编码实战
linux·服务器·c语言·c++·嵌入式硬件·嵌入式软件·dbus
淼澄研学12 小时前
Kimi API黑产倒卖技术解析与Python合规接入指南
开发语言·网络·python
冻柠檬飞冰走茶12 小时前
PTA基础编程题目集 7-35有理数均值(C++语言实现)
开发语言·数据结构·c++·算法·均值算法
wangchen_012 小时前
C++正则表达式
开发语言·c++·正则表达式
何以解忧,唯有..12 小时前
Python 元组(tuple)详解:使用、遍历与排序
开发语言·python
KANGBboy12 小时前
Python eval安全隐患
开发语言·python
IT爱学堂12 小时前
java版数据结构和算法+AI算法和技能学习指南
java·开发语言
淼澄研学13 小时前
Python结合大模型挖掘搜题长尾关键词实操指南
开发语言·python
FfHUCisI13 小时前
Golang - 信号量模式(Semaphore Pattern)
开发语言·后端·golang