如何在運行時遞回地將檔案夾及其所有子檔案夾的權限更改為 0777?
代碼是c ,mac。我包括 <sys/stat.h> chmod,但是沒有關于如何遞回執行的檔案。
uj5u.com熱心網友回復:
最簡單和最便攜的方法是使用std::filesystem在 C 17 中添加的庫。在那里,您會找到一個recursive_directory_iterator和許多其他方便的類和函式來處理檔案系統特定的事情。
例子:
#include <filesystem>
#include <iostream>
namespace fs = std::filesystem;
void chmodr(const fs::path& path, fs::perms perm) {
fs::permissions(path, perm); // set permissions on the top directory
for(auto& de : fs::recursive_directory_iterator(path)) {
fs::permissions(de, perm); // set permissions
std::cout << de << '\n'; // debug print
}
}
int main() {
chmodr("your_top_directory", fs::perms::all); // perms::all = 0777
}
但是,recursive_directory_iterator當涉及的目錄太多時會出現問題。它可能會用完檔案描述符,因為它需要保持許多目錄處于打開狀態。出于這個原因,我更喜歡使用 adirectory_iterator來代替 - 并收集子目錄以供以后檢查。
例子:
#include <filesystem>
#include <iostream>
#include <vector>
namespace fs = std::filesystem;
void chmodr(const fs::path& path, fs::perms perm) {
std::vector<fs::path> subdirs;
fs::permissions(path, perm);
for(auto& de : fs::directory_iterator(path)) {
// save subdirectories for later:
if(fs::is_directory(de)) subdirs.push_back(de);
else fs::permissions(de, perm);
}
// now go through the subdirectories:
for(auto& sd : subdirs) {
chmodr(sd, perm);
}
}
int main() {
chmodr("your_top_directory", fs::perms::all);
}
您可以在我在頂部提供的鏈接中閱讀示例中使用的std::filesystem::(fs::在上面的代碼中)函式、類和權限列舉。
在某些實作中,只有部分 C 17 支持,您可能會filesystem在其中找到experimental/filesystem。如果是這種情況,您可以替換上面的
#include <filesystem>
namespace fs = std::filesystem;
#ifdef我在這個答案中提供的叢林。
轉載請註明出處,本文鏈接:https://www.uj5u.com/caozuo/431598.html
