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;
}
相关推荐
blasit21 小时前
笔记:Qt C++建立子线程做一个socket TCP常连接通信
c++·qt·tcp/ip
肆忆_2 天前
# 用 5 个问题学懂 C++ 虚函数(入门级)
c++
不想写代码的星星2 天前
虚函数表:C++ 多态背后的那个男人
c++
端平入洛4 天前
delete又未完全delete
c++
端平入洛5 天前
auto有时不auto
c++
郑州光合科技余经理6 天前
代码展示:PHP搭建海外版外卖系统源码解析
java·开发语言·前端·后端·系统架构·uni-app·php
feifeigo1236 天前
matlab画图工具
开发语言·matlab
dustcell.6 天前
haproxy七层代理
java·开发语言·前端
norlan_jame6 天前
C-PHY与D-PHY差异
c语言·开发语言
哇哈哈20216 天前
信号量和信号
linux·c++