std::filesystem::directory_entry::is_socket
来自cppreference.com
< cpp | filesystem | directory entry
bool is_socket()const; | (1) | (C++17 起) |
bool is_socket(std::error_code& ec )constnoexcept; | (2) | (C++17 起) |
检查所指对象是否为具名套接字。各自等效于返回:
1)std::filesystem::is_socket(status()),
2)std::filesystem::is_socket(status(ec))。
目录 |
[编辑]参数
ec | - | 不抛出重载中报告错误的输出形参 |
[编辑]返回值
若所引用文件系统对象是具名接头则为 true,否则为 false。
[编辑]异常
若内存分配失败,则任何不标记为 noexcept
的重载可能抛出 std::bad_alloc 。
[编辑]示例
运行此代码
#include <cstdio>#include <cstring>#include <filesystem>#include <fstream>#include <functional>#include <iostream>#include <memory>#include <sys/socket.h>#include <sys/stat.h>#include <sys/un.h>#include <unistd.h> namespace fs = std::filesystem; void print_entry_type(conststd::filesystem::directory_entry& entry){std::cout<< entry.path()<<": "; if(!entry.exists())std::cout<<"不存在";if(entry.is_block_file())std::cout<<"是块设备";if(entry.is_character_file())std::cout<<"是字符设备";if(entry.is_directory())std::cout<<"是目录";if(entry.is_fifo())std::cout<<"是具名 IPC 管道";if(entry.is_regular_file())std::cout<<"是常规文件";if(entry.is_socket())std::cout<<"是具名 IPC 套接字";if(entry.is_symlink())std::cout<<" (符号链接)";if(entry.is_other())std::cout<<" (`other` 文件)"; std::cout<<'\n';} template<typename Type, typename Fun>class scoped_cleanup {std::unique_ptr<Type, std::function<void(const Type*)>> u; public: scoped_cleanup(Type* ptr, Fun fun): u{ptr, std::move(fun)}{}}; int main(){// 创建不同种类的文件:std::filesystem::current_path(fs::temp_directory_path());conststd::filesystem::path sandbox{"sandbox"}; scoped_cleanup remove_all_at_exit{&sandbox, [](const fs::path* p){std::cout<<"清理: remove_all("<<*p <<")\n"; fs::remove_all(*p);}};std::filesystem::create_directory(sandbox);std::ofstream{sandbox/"file"};// 创建常规文件std::filesystem::create_directory(sandbox/"dir"); mkfifo((sandbox/"pipe").string().data(), 0644);struct sockaddr_un addr; addr.sun_family= AF_UNIX; std::strcpy(addr.sun_path, (sandbox/"sock").string().data());int fd{socket(PF_UNIX, SOCK_STREAM, 0)}; scoped_cleanup close_socket_at_exit{&fd, [](constint* f){std::cout<<"清理: 关闭套接字 #"<<*f <<'\n'; close(*f);}}; bind(fd, reinterpret_cast<sockaddr*>(std::addressof(addr)), sizeof addr); fs::create_symlink("file", sandbox/"symlink"); for(std::filesystem::directory_entry entry: fs::directory_iterator(sandbox)) print_entry_type(entry); // 直接请求文件系统对象状态:for(constchar* str :{"/dev/null", "/dev/cpu", "/usr/include/c++", "/usr/include/asm", "/usr/include/time.h"}) print_entry_type(fs::directory_entry{str}); }// 通过 scoped_cleanup 对象进行清理
可能的输出:
"sandbox/symlink": 是常规文件 (符号链接) "sandbox/sock": 是具名 IPC 套接字 (`other` 文件) "sandbox/pipe": 是具名 IPC 管道 (`other` 文件) "sandbox/dir": 是目录 "sandbox/file": 是常规文件 "/dev/null": 是字符设备 (`other` 文件) "/dev/cpu": 不存在 "/usr/include/c++": 是目录 "/usr/include/asm": 是目录 (符号链接) "/usr/include/time.h": 是常规文件 清理: 关闭套接字 #3 清理: remove_all("sandbox")
[编辑]参阅
(C++17) | 检查参数是否表示一个具名 IPC 套接字 (函数) |