C++文件處理與C語言不同,C++文件處理使用的是:流(stream)
C++頭文件fstream
定義了三個類型來支持文件IO👇
- ifstream從一個給定文件中讀取數據
- ofstream向一個給定文件寫入數據
- fstream可以讀寫文件
這些類型提供的操作與我們之前已經使用過的cin
和cout
操作一樣。特別是,我們可以使用IO運算符(>>和<<)來讀寫文件,也可使用getline
從一個ifstream中讀取數據。
一、讀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: 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;
}
二、寫txt文件
main()函數如下,main()函數之前的部分同上
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;
out_file << "Have a Nice Day!" << endl;
} else {
cout << "Cannot Open File: " << path << endl;
getchar();
return EXIT_FAILURE;
}
out_file.close();
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()) << path;std::string line;
std::string item;while (std::getline(file, line)) {
StringTrim(&line);if (line.empty() || line[0] == '#') { continue; } std::stringstream line_stream(line); class Camera camera; // ID std::getline(line_stream, item, ' '); camera.SetCameraId(std::stoul(item)); // MODEL std::getline(line_stream, item, ' '); camera.SetModelIdFromName(item); // WIDTH std::getline(line_stream, item, ' '); camera.SetWidth(std::stoll(item)); // HEIGHT std::getline(line_stream, item, ' '); camera.SetHeight(std::stoll(item)); // PARAMS camera.Params().clear(); while (!line_stream.eof()) { std::getline(line_stream, item, ' '); camera.Params().push_back(std::stold(item)); } CHECK(camera.VerifyParams()); cameras_.emplace(camera.CameraId(), camera);
}
}
參考
- C++ Primer 第五版
- Reading from a Text File