C++文件处理与C语言不同,C++文件处理使用的是:流(stream)
C++头文件fstream定义了三个类型来支持文件IO👇
- ifstream从一个给定文件中读取数据
- ofstream向一个给定文件写入数据
- fstream可以读写文件
这些类型提供的操作与我们之前已经使用过的cin和cout操作一样。特别是,我们可以使用IO运算符(>>和<<)来读写文件,也可使用getline从一个ifstream中读取数据。

读取txt文件,并逐行打印
现有cameras.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: Programmer ToddyQi
// Date: 2020-02-12
#include <iostream>
#include <fstream> // 头文件 For both fstream and ifstream
#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;
}

Code is Here: 点击查看详细内容 TODO
// 解析cameras.txt文件
void Reconstruction::ReadCamerasText(const std::string& path) {
cameras_.clear();
std::ifstream file(path);
CHECK(file.is_open())
参考
- C++ Primer 第五版
- Reading from a Text File
来源:https://www.cnblogs.com/Todd-Qi/p/11367701.html