C++文件处理(一):读/写文本文件

前言

C++文件处理与C语言不同,C++文件处理使用的是:流(stream)
C++头文件#include <fstream>定义了三个类型来支持文件IO👇

  • ifstream从一个给定文件中读取数据
  • ofstream向一个给定文件写入数据
  • fstream可以读写文件(支持ifstream和ofstream的操作)

这些类型提供的操作与我们之前已经使用过的cincout操作一样。特别是,我们可以使用IO运算符(>>和<<)来读写文件,也可使用getline从一个ifstream中读取数据。

图1. fstream特有的操作(图片来源于参考[1])

一、读txt文件

现有cameras.txt文件,内容如下👇
读取txt文件,并逐行打印

# Camera list with one line of data per camera:
#   CAMERA_ID, MODEL, WIDTH, HEIGHT, PARAMS[]
# Number of cameras: 1
0 PINHOLE 6220 4141 3430.27 3429.23 3119.2 2057.75
// Author: Todd-Qi
// Date: 2020-02-12
#include <iostream>
#include <fstream>    // 头文件 For both ifstream and ofstream
#include <string>

using namespace std;

int main() {
	string path = "./cameras.txt";
	
	ifstream in_file(path, ios::in); //按照指定mode打开文件
	
	// is_open()函数返回一个bool值,指出与in_file关联的文件是否成功打开且未关闭
	if (in_file.is_open()) { // 或者if (in_file)
		cout << "Open File Successfully" << endl;
		string line;
		while(getline(in_file, line)) {
			cout << line << endl;
			}		
	} else {
		cout << "Cannot Open File: " << path << endl;
		getchar();
		return EXIT_FAILURE;
	}
	in_file.close(); // 关闭与in_file绑定的文件,返回void
	
	getchar();
	return EXIT_SUCCESS;
}

图2. 实验运行结果

二、写txt文件

main()函数如下,main()函数之前的部分同上

#include <iostream>
#include <fstream>    // 头文件 For both ifstream and ofstream
#include <string>

using namespace std;

int main()
{
	string path = "./log.txt";

	ofstream out_file(path, ios::out | ios::app); //按照指定mode打开文件
	// ofstream out_file(path, ios::out);

	if (out_file.is_open()) {
		cout << "Open File Successfully" << endl;  // 写txt文件的语法同cout控制台打印
		out_file << "Have a Nice Day!" << endl;	   // 区别在于:写文件(ofstream) / 控制台打印(iostream)
	} else {
		cout << "Cannot Open File: " << path << endl;
		getchar();
		return EXIT_FAILURE;
	}
	out_file.close();

	getchar();
	return EXIT_SUCCESS;
}

图3. 实验运行结果

三、文件读写的不同mode

使用open函数打开文件:

void open(const char* filename, int mode)

第一个参数为文件名,第二个参数指定文件打开的模式。文件的打开模式标记代表了文件的使用方式,这些标记可以单独使用,也可以组合使用。

模式标记 适用对象 描述
ios::out ofstream/fstream 存在则会覆盖
ios::app ofstream/fstream 存在则会在文件末尾添加 (append)

参考

posted @ 2020-02-13 10:58  达可奈特  阅读(3321)  评论(0编辑  收藏  举报