C++ filesystem 文件系统初体验

#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);
        }
    }
}

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值