C++文件操作

发布于:2024-06-16 ⋅ 阅读:(14) ⋅ 点赞:(0)

简述:

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;
	ofs.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;
		}
	}
	ofs.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;
	ofs.open("E:\\桌面材料\\新建文件夹\\新建 文本文档.txt", ios::in);
	if(!ifs.is_open()) {
		cout<<"error!"<<endl;
	} else {
		char c;
		while((c = ifs.get()) != EOF) {
			cout<<c;
		}
	}
	ofs.close();
	return 0;
}