gpt4 book ai didi

C++ recursive_directory_iterator 遗漏一些文件

转载 作者:行者123 更新时间:2023-11-30 03:19:19 31 4
gpt4 key购买 nike

我试图在我的 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 . <filesystem> 可能使用 wchar_t* 操作字符串,因为你在 Windows 上。使用 SHGetKnownFolderPath(...)查询特殊文件夹的位置。

当您运行您的程序时会发生什么,可能是您遇到了一些您当前语言环境无法显示的字符(如果未明确设置,则为“C”),因此它会将您的外流设置为失败模式。但是,您可以将语言环境设置为 UTF-16LE 来解决这个问题。它适用于/std:c++17 和标准 <filesystem> header :

#include <Shlobj.h> // SHGetKnownFolderPath
#include <clocale> // std::setlocale
#include <io.h> // _setmode
#include <fcntl.h> // _O_U16TEXT

Code Page Identifiers

const char CP_UTF_16LE[] = ".1200";
setlocale(LC_ALL, CP_UTF_16LE);

_setmode

_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);
}

您还可以找到 Default Known Folders 的列表在 Windows 中很有用。

关于C++ recursive_directory_iterator 遗漏一些文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53821593/

31 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com