我正在编写一个 linux 命令行程序,它将返回目录的大小。该程序按预期工作,除非专门处理根目录。我知道根目录中的许多文件没有大小,因为它们是用于表示系统信息(如 /proc/)或 /dev/null/ 之类的特殊文件,所以我std::filesystem::directory_options::skip_permission_denied在 for 循环中使用以跳过权限问题,我使用多个 try/catch 块来捕获异常。
但是,即使这样,仍然会抛出权限被拒绝的异常。请参阅以下代码:
byte_size_and_num_files find_recursive(const std::filesystem::path& path)
{
byte_size_and_num_files bsnf;
std::filesystem::path pa;
try
{
for(const auto& p: std::filesystem::recursive_directory_iterator(path, std::filesystem::directory_options::skip_permission_denied))
{
pa = p.path();
if (std::filesystem::exists(p) && !std::filesystem::is_directory(p))
{
try
{
if(std::filesystem::is_regular_file(pa))
{
bsnf.size += std::filesystem::file_size(p);
bsnf.files++;
}
else
std::cout << "SKIPPED: size is not determinable: " << pa << "\n";
}
catch(std::filesystem::filesystem_error& e)
{
std::cout << "SKIPPED: size is not determinable: " << pa << "\n";
}
catch(std::bad_alloc)
{
std::cout …Run Code Online (Sandbox Code Playgroud)