C++17 C17 中的新增功能std::filesystem

本文主要介绍C++17 / C17中的filesystem中的一些常用方法。

C17中新增了filesystem功能,使得跨平台文件系统 操作使用便方便简易。

一、windows环境下

使用Visual Studio开发必须要vs2019才支持C++17新特性。

VS2019默认不使用C17新特性,如需使用要手动打开此功能。

二、linux环境下

使用g++编译器,gcc编译器必须要升级到g++ 10.0.1版本才支持C++17的新特性。

三、使用详情

包含相关头文件#include <filesystem>。

头文件及命名空间:

#include <filesystem>
using namespace std::filesystem;

1、常用类:

    path 类:说白了该类只是对字符串(路径)进行一些处理,这也是文件系统的基石。

    directory_entry 类:功如其名,文件入口,这个类才真正接触文件。 

    directory_iterator 类:获取文件系统目录中文件的迭代器容器,其元素为 directory_entry对象(可用于遍历目录)

    file_status 类:用于获取和修改文件(或目录)的属性(需要了解C++11的强枚举类型(即枚举类))

2、常用方法:

    std::filesystem::is_directory()检查是否为目录;

    std::filesystem::current_path()返回当前路径;

    std::filesystem::exists()文件目录是否存在;

    std::filesystem::create_directories()创建目录,可以连续创建多级目录;

3、使用实例:

//遍历一个目录
bool TravelFolder(const std::string& strdir)
{
    std::filesystem::path pathpath(strdir);
    if (!std::filesystem::exists(pathpath))
    {
        return false;
    }
    if (!std::filesystem::is_directory(pathpath))
    {
        return false;
    }
    std::filesystem::directory_entry direntry(pathpath);
    if (direntry.status().type() == std::filesystem::file_type::directory)
    {
        //TODO something....
    }
    std::filesystem::directory_iterator dirite(pathpath);
    for (auto& ite : dirite)
    {
        if (ite.status().type() == std::filesystem::file_type::directory) //is folder
        {
            std::string strsubdir = ite.path().string();
            TravelFolder(strsubdir);
        }
        else if (ite.status().type() == std::filesystem::file_type::regular) //is file
        {
            //TODO other....
            std::string strfile = ite.path().filename().string();
        }
    }
    return true;
}

4.常用库函数:

void copy(const path& from, const path& to) ;//目录复制

path absolute(const path& pval, const path& base = current_path()) ;//获取相对于base的绝对路径

bool create_directory(const path& pval) ;//当目录不存在时创建目录

bool create_directories(const path& pval) ;//形如/a/b/c这样的,如果都不存在,创建目录结构

bool exists(const path& pval) ;//用于判断path是否存在

uintmax_t file_size(const path& pval) ;//返回目录的大小

file_time_type last_write_time(const path& pval) ;//返回目录最后修改日期的file_time_type对象

bool remove(const path& pval) ;//删除目录

uintmax_t remove_all(const path& pval) ;//递归删除目录下所有文件,返回被成功删除的文件个数

void rename(const path& from, const path& to) ;//移动文件或者重命名

猜你喜欢

转载自blog.csdn.net/shaderdx/article/details/108235666
C17