![](/img/trans.png)
[英]How to use recursive_directory_iterator(..) without exceptions in C++
[英]C++ recursive_directory_iterator miss some files
我正在嘗試通過Visual Studio 2017上的c ++ 17獲取目錄中的所有文件,但我剛遇到一個非常奇怪的問題。 如果我這樣指定目錄,則可以毫無問題地獲取所有文件:
for (auto& p : std::filesystem::recursive_directory_iterator("C:\\Users\\r00t\\AppData\\Roaming\\Mozilla")) {
if (std::filesystem::is_regular_file(p.path())) {
std::cout << p.path() << std::endl;
}
}
但是我需要APPDATA上的所有文件列表,並且我嘗試使用getenv()函數獲取路徑,並且在使用它時,“ recursive_directory_iterator”函數會跳過文件:
for (auto& p : std::filesystem::recursive_directory_iterator(getenv("APPDATA"))) {
if (std::filesystem::is_regular_file(p.path())) {
std::cout << p.path() << std::endl;
}
}
那是因為使用了getenv()函數嗎? 一些使用getenv時會跳過的文件夾;
Mozilla
TeamWiever
NVIDIA
等等 ..
順便說一句,我最近5天一直在使用C ++,並且絕對不知道導致這種現象的原因。 請幫助我,現在我被困住了。
編輯:
for (auto& p : std::filesystem::directory_iterator(getenv("APPDATA"))) {
std::string targetFolder = p.path().string();
for (auto& targetFolderFiles : std::filesystem::recursive_directory_iterator(targetFolder)) {
if (std::filesystem::is_regular_file(targetFolderFiles.path())) {
std::cout << targetFolderFiles.path() << std::endl;
}
}
}
這也不起作用,似乎我必須將字符串放入這樣的函數中:
recursive_directory_iterator("C:\\Users\\r00t\\AppData\\Roaming\\Mozilla")
否則肯定無法正常工作,大聲笑?
編輯-問題已解決
如預期的那樣,使用實驗庫可與C ++ 14編譯器一起使用。
#include <experimental/filesystem>
現在我可以毫無問題地獲取所有文件了。似乎這是關於C ++ 17和文件系統庫的問題..感謝所有支持人員。
getenv()
返回char*
或NULL
。 由於您在Windows上, <filesystem>
可能與wchar_t*
字符串一起運行。 使用SHGetKnownFolderPath(...)
查詢特殊文件夾的位置。
運行程序時發生的情況可能是您擊中了某些無法在當前語言環境下顯示的字符(如果未明確設置,則為“ C”),因此將您的流媒體設置為失敗模式。 但是,您可以將語言環境設置為UTF-16LE來解決此問題。 它與/ std:c ++ 17和標准的<filesystem>
標頭一起使用:
#include <Shlobj.h> // SHGetKnownFolderPath
#include <clocale> // std::setlocale
#include <io.h> // _setmode
#include <fcntl.h> // _O_U16TEXT
const char CP_UTF_16LE[] = ".1200";
setlocale(LC_ALL, CP_UTF_16LE);
_setmode(_fileno(stdout), _O_U16TEXT);
有了這個,從SHGetKnownFolderPath
獲得的路徑應該可以正常工作:
PWSTR the_path;
if(SHGetKnownFolderPath(FOLDERID_RoamingAppData, KF_FLAG_DEFAULT, NULL, &the_path) == S_OK) {
for(auto& p : std::filesystem::recursive_directory_iterator(the_path)) {
std::wcout << p.path() << L"\n";
// you can also detect if the outstream is in fail mode:
if (std::wcout.fail()) {
std::wcout.clear(); // ... and clear the fail mode
std::wcout << L" (wcout was fail mode)\n";
}
}
CoTaskMemFree(the_path);
}
您可能還會發現Windows中的“ 默認已知文件夾 ”列表很有用。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.