2017-10-19 239 views
0

是否有跨平台的方式递归设置C++文件夹内容的权限?设置C++文件夹中所有文件的权限

我不想依赖系统调用。

+0

[Qt的](https://www.qt.io)具有类,可以帮助你。 –

+0

非*所有*平台都支持文件夹,尤其是嵌入式系统区域中的文件夹。 –

回答

0

实施例用C++ 17及其std::filesystem授予0777到目录中的所有文件和文件夹:

代码:

#include <exception> 
//#include <filesystem> 
#include <experimental/filesystem> // Use this for most compilers as of yet. 

//namespace fs = std::filesystem; 
namespace fs = std::experimental::filesystem; // Use this for most compilers as of yet. 

int main() 
{ 
    fs::path directory = "change/permission/of/descendants"; 
    for (auto& path : fs::recursive_directory_iterator(directory)) 
    { 
     try { 
      fs::permissions(path, fs::perms::all); // Uses fs::perm_options::replace. 
     } 
     catch (std::exception& e) { 
      // Handle exception or use another overload of fs::permissions() 
      // with std::error_code. 
     }   
    } 
} 

如果如fs::perm_options::add而不是fs::perm_options::replace是需要的,那么这还不是跨平台的。而VS17的experimental/filesystem不知道fs::perm_options,并且包括addremove作为fs::perms::add_permsfs::perms::remove_perms。这意味着的std::filesystem::permissions签名是稍有不同:

标准:

fs::permissions(path, fs::perms::all, fs::perm_options::add); 

VS17:

fs::permissions(path, fs::perms::add_perms | fs::perms::all); // VS17. 
+0

你有没有考虑过boost:文件系统? – drescherjm

+0

既然你提到这个Visual Studio的不兼容性,这是为了答案,或者你在寻找其他答案,这个材料应该是在问题? – drescherjm

+0

@drescherjm我选择这个作为答案,因为只要'perm_options'没有手动设置,它就会工作。然而,第二部分的b/c确实也适用于这个问题。对不起,我在创建问题时没有看到。 –