1 std::filesystem

C++17的std::filesystem提供了下列判断文件类型的函数:

  • std::filesystem::is_block_file:判断文件路径是否引用块设备

  • std::filesystem::is_character_file:判断文件路径是否引用符设备

  • std::filesystem::is_directory:判断文件路径是否引用目录

  • std::filesystem::is_empty:判断文件路径是否是空文件或者目录

  • std::filesystem::is_fifo:判断文件路径是否引用命名管道

  • std::filesystem::is_other:判断文件路径是否引用其他文件

  • std::filesystem::is_regular_file:判断文件路径是否引用常规文件

  • std::filesystem::is_socket:判断文件路径是否引用socket套接字

  • std::filesystem::is_symlink:判断文件路径是否引用符号链接

使用示例代码

#include<iostream>
#include <filesystem>

void PrintFileType(const std::filesystem::path& path)
{
    if (!std::filesystem::exists(path))
    {
        std::cout << path << " is not exist" << std::endl;
        return;
    }

    if (std::filesystem::is_regular_file(path))
    {
        std::cout << path << " is a regular file" << std::endl;
    }
    else if (std::filesystem::is_directory(path))
    {
        std::cout << path << " is a directory" << std::endl;
    }
    else if (std::filesystem::is_block_file(path))
    {
        std::cout << path << " is a block device" << std::endl;
    }
    else if (std::filesystem::is_character_file(path))
    {
        std::cout << path << " is a character device" << std::endl;
    }
    else if (std::filesystem::is_fifo(path))
    {
        std::cout << path << " is a named IPC pipe" << std::endl;
    }
    else if (std::filesystem::is_socket(path))
    {
        std::cout << path << " is a named IPC socket" << std::endl;
    }
    else if (std::filesystem::is_symlink(path))
    {
        std::cout << path << " is a symlink" << std::endl;
    }
}

int main()
{
    std::string file_path = "E:\\example.txt";
    std::filesystem::path temp_filesystem(file_path);

    PrintFileType(temp_filesystem);

    return 0;
}