C++17 filesystem

C++终于在17中增加了对文件系统的支持,在这之前C++程序员只能使用POSIX接口或者windowsAPI去做一些目录操作。 下面来看看怎么使用吧。

注:

filesystem中,所有的文件、路径,都抽象成了path这个类,其成员函数可以获取各种类型的路径名、拼接路径名、修改扩展名等。并且由于重载了operator/=,因此还可以用/符号来拼接两个path对象。这个类可以理解成针对路径进行特化的一个字符串类,它不包含一些更高级的操作。举例:

#include <iostream>
#include <filesystem>

namespace fs = std::filesystem;

int main() {
    fs::path exampleFile = "D:\\_workspace\\png\\1.png";
    printf("string: %s\n", exampleFile.string().c_str());
    printf("generic_string: %s\n", exampleFile.generic_string().c_str());
    printf("root_name: %s\n", exampleFile.root_name().string().c_str());
    printf("root_directory: %s\n", exampleFile.root_directory().string().c_str());
    printf("root_path: %s\n", exampleFile.root_path().string().c_str());
    printf("relative_path: %s\n", exampleFile.relative_path().string().c_str());
    printf("parent_path: %s\n", exampleFile.parent_path().string().c_str());
    printf("filename: %s\n", exampleFile.filename().string().c_str());
    printf("stem: %s\n", exampleFile.stem().string().c_str());
    printf("extension: %s\n", exampleFile.extension().string().c_str());
}

输出为:

string:          D:\_workspace\png\1.png
generic_string:  D:/_workspace/png/1.png
root_name:       D:
root_directory:  \
root_path:       D:\
relative_path:   _workspace\png\1.png
parent_path:     D:\_workspace\png
filename:        1.png
stem:            1
extension:       .png

更高级的操作需要用到directory_entry这个类,它包含的操作有:检查路径是否存在、检查路径的类型(是目录还是文件还是软链接)、获取路径占用空间的大小、获取路径的修改时间等。

当需要遍历一个目录时,需要用到directory_iterator类。

下面结合directory_entry和directory_iterator举个栗子,比如我要遍历目录A,获取A中的所有后缀为png的图片,在目录B中创建与其文件名相同但后缀不同的jpg文件:

#include <iostream>
#include <filesystem>

namespace fs = std::filesystem;

int main() {
    fs::path srcDir = "D:\\_workspace\\png";
    fs::path dstDir = "D:\\_workspace\\jpg";
    if (!fs::exists(srcDir)) {
        return -1;
    }
    if (!fs::exists(dstDir)) {
        fs::create_directory(dstDir); //不存在则创建
    }
    // 遍历directory_iterator获取每个directory_entry
    for (const fs::directory_entry &entry: fs::directory_iterator(srcDir)) {
        // 若是文件,且后缀是png
        if (entry.is_regular_file() and entry.path().extension() == ".png") {
            printf("%s\n", entry.path().string().c_str());
            // 替换后缀
            fs::path dstFileName = entry.path().filename().replace_extension("jpg");
            // 拼接生成新的文件名
            fs::path dst = dstDir / dstFileName;
            printf("%s\n", dst.string().c_str());
        }
    }
}

  • 4
    点赞
  • 15
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值