Abel'Blog

我干了什么?究竟拿了时间换了什么?

0%

C++17-filesystem

简介

记录一下filesystem相关知识,需要开启c++17标准。

path相关操作

目录操作

1
2
3
4
// 获取绝对路径
std::filesystem::absolute(std::filesystem::current_path().append(filename_));
// 获得目录分割
std::filesystem::path::preferred_separator;

遍历目录

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
###include <fstream>
###include <iostream>
###include <filesystem>
namespace fs = std::filesystem;

int main()
{
fs::create_directories("sandbox/a/b");
std::ofstream("sandbox/file1.txt");
std::ofstream("sandbox/file2.txt");
for(auto& p: fs::directory_iterator("sandbox"))
std::cout << p.path() << '\n';
fs::remove_all("sandbox");
}

output:
"sandbox/a"
"sandbox/file1.txt"
"sandbox/file2.txt"

获取文件名

1
2
auto log_path = fs::absolute(log_path_).string();
auto logger_name = fs::path(log_path).stem().string();

注意

使用此库可能要求额外的编译器/链接器选项。 9.1 前的 GNU 实现要求用 -lstdc++fs 链接,而 LLVM 9.0 前的 LLVM 实现要求用 -lc++fs 链接。

引用