c++17 判断是目录或者文件

创建日期: 2024-06-05 15:40 | 作者: 风波 | 浏览次数: 14 | 分类: C++

来源:https://stackoverflow.com/questions/146924/how-can-i-tell-if-a-given-path-is-a-directory-or-a-file-c-c

#include <filesystem> // C++17
#include <iostream>
namespace fs = std::filesystem;

int main()
{
    const std::string pathString = "/my/path";
    const fs::path path(pathString); // Constructing the path from a string is possible.
    std::error_code ec; // For using the non-throwing overloads of functions below.
    if (fs::is_directory(path, ec))
    { 
        // Process a directory.
    }
    if (ec) // Optional handling of possible errors.
    {
        std::cerr << "Error in is_directory: " << ec.message();
    }
    if (fs::is_regular_file(path, ec))
    {
        // Process a regular file.
    }
    if (ec) // Optional handling of possible errors. Usage of the same ec object works since fs functions are calling ec.clear() if no errors occur.
    {
        std::cerr << "Error in is_regular_file: " << ec.message();
    }
}

C++14

In C++14 use std::experimental::filesystem.

#include <experimental/filesystem> // C++14
namespace fs = std::experimental::filesystem;
14 浏览
9 爬虫
0 评论