c recursive_directory_iterator错过了一些文件

C++ recursive_directory_iterator miss some files

本文关键字:错过了 文件 iterator recursive directory      更新时间:2023-10-16

我正在尝试通过CHISVIOS 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(...)查询特殊文件夹的位置。

运行程序时会发生什么,可能是您击中无法用当前语言环境显示的某些角色(如果未明确设置),因此它将您的沿线设置为失败模式。但是,您可以将其设置为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

_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中找到默认已知文件夹的列表。