- 需要有环境 [[Linux怎样更新Centos下Gcc版本支持C17?]]
- 代码需要在编译时指定 c++版本
- 如果使用多线程和锁,要加-pthread
- 使用文件系统类,需要额外的编译选项 -lstdc++fs
- 不需要额外指定动态库或者静态库地址,filesystem类包含在了libstdc++.so中
-rw-r--r-- 1 root root 4887654 Mar 27 2020 libstdc++.a -rw-r--r-- 1 root root 1520198 Mar 27 2020 libstdc++fs.a -rw-r--r-- 1 root root 1928418 Mar 27 2020 libstdc++_nonshared.a -rw-r--r-- 1 root root 210 Mar 27 2020 libstdc++.so
以下为示例:通过c++17的新特性实现对文件的读取。
源码
#include <iostream> #include <fstream> #include <string> #include <vector> #include <map> #include <filesystem> #include <thread> #include <mutex> using namespace std; namespace fs = std::filesystem; class FileScanner { public: FileScanner(string path, bool recursive = true, bool parallel = false) : path_(path), recursive_(recursive), parallel_(parallel) {} map<string, string> search() { map<string, string> result; vector<thread> threads; mutex m; if (parallel_) { for (auto &p : fs::recursive_directory_iterator(path_)) { if (!fs::is_directory(p)) { threads.emplace_back([&]() { auto file_path = p.path().string(); auto file_name = p.path().filename().string(); ifstream file(file_path); if (file) { string content((istreambuf_iterator<char>(file)), istreambuf_iterator<char>()); lock_guard<mutex> lock(m); result[file_name] = content; } }); } } } else if (recursive_) { for (auto &p : fs::recursive_directory_iterator(path_)) { if (!fs::is_directory(p)) { auto file_path = p.path().string(); auto file_name = p.path().filename().string(); ifstream file(file_path); if (file) { string content((istreambuf_iterator<char>(file)), istreambuf_iterator<char>()); result[file_name] = content; } } } } else { for (auto &p : fs::directory_iterator(path_)) { if (!fs::is_directory(p)) { auto file_path = p.path().string(); auto file_name = p.path().filename().string(); ifstream file(file_path); if (file) { string content((istreambuf_iterator<char>(file)), istreambuf_iterator<char>()); result[file_name] = content; } } } } if (parallel_) { for (auto &thread : threads) { thread.join(); } } return result; } private: string path_; bool recursive_; bool parallel_; }; int main() { FileScanner scanner("path/to/your/directory", true, true); map<string, string> result = scanner.search(); for (auto &item : result) { cout << item.first << " : " << item.second << endl; } return 0; }
编译方式:
g++ ReadFileDemo-4.cpp -std=c++17 -lstdc++fs -pthread -g -o Read_Test-4