#include <filesystem>
#include <iostream>
using namespace std;
// 递归输出文件夹内容
void ls(filesystem::path d);
int main() {
filesystem::path path(filesystem::current_path());
// // 或者用相对路径表示
// filesystem::path path(".");
// 输出绝对/相对路径
cout << filesystem::absolute(path) << "\n";
cout << filesystem::relative(path) << "\n";
// 创建目录条目
filesystem::directory_entry entry(path);
// 输出目录信息
// 输入`list -l`即可查看目录信息,比如drwxr-xr-x
cout << "Is a directory? " << (entry.status().type() == filesystem::file_type::directory ? "yes" : "no") << "\n";
cout << "Is a regular file? " << (entry.status().type() == filesystem::file_type::regular ? "yes" : "no") << "\n";
cout << "Can owner write? " << ((bool)(entry.status().permissions() & filesystem::perms::owner_write) ? "yes" : "no") << "\n";
// path类型支持的操作符`/`
filesystem::path file(path / "filesystem.cpp");
cout << file.filename() << " exists? " << (filesystem::exists(file) ? "yes" : "no") << "\n";
// 遍历目录内容
filesystem::directory_iterator iter(entry);
for (auto item : iter) {
if (filesystem::is_directory(item)) {
cout << "[" << item.path().filename() << "]\n";
} else {
cout << item.path().filename() << " = "; // 文件名
cout << item.path().stem() << " + "; // 文件根
cout << item.path().extension() << "\n"; // 扩展名
}
}
// 递归输出文件夹内容
ls(entry.path().parent_path());
}
// 递归输出文件夹内容
void ls(filesystem::path d) {
if (!filesystem::is_directory(d)) {
cerr << "Argument is not a directory\n";
return;
}
filesystem::directory_iterator iter(d);
for (auto item : iter) {
cout << item.path() << "\n";
if (filesystem::is_directory(item)) {
ls(item);
}
}
}
C++ filesystem 文件系统初体验
最新推荐文章于 2023-07-18 17:27:57 发布