如何使用C++列出Windows中的子目录?

ave*_*vee 7 c++ windows subdirectory

如何使用C++列出Windows中的子目录?使用可以运行跨平台的代码会更好.

ave*_*vee 7

这是我针对该问题的解决方案,尽管它只是Windows解决方案。我想使用跨平台解决方案,但不使用Boost。

#include <Windows.h>
#include <vector>
#include <string>

/// Gets a list of subdirectories under a specified path
/// @param[out] output Empty vector to be filled with result
/// @param[in]  path   Input path, may be a relative path from working dir
void getSubdirs(std::vector<std::string>& output, const std::string& path)
{
    WIN32_FIND_DATA findfiledata;
    HANDLE hFind = INVALID_HANDLE_VALUE;

    char fullpath[MAX_PATH];
    GetFullPathName(path.c_str(), MAX_PATH, fullpath, 0);
    std::string fp(fullpath);

    hFind = FindFirstFile((LPCSTR)(fp + "\\*").c_str(), &findfiledata);
    if (hFind != INVALID_HANDLE_VALUE)
    {
        do 
        {
            if ((findfiledata.dwFileAttributes | FILE_ATTRIBUTE_DIRECTORY) == FILE_ATTRIBUTE_DIRECTORY
                && (findfiledata.cFileName[0] != '.'))
            {
                output.push_back(findfiledata.cFileName);
            }
        } 
        while (FindNextFile(hFind, &findfiledata) != 0);
    }
}

/// Gets a list of subdirectory and their subdirs under a specified path
/// @param[out] output Empty vector to be filled with result
/// @param[in]  path   Input path, may be a relative path from working dir
/// @param[in]  prependStr String to be pre-appended before each result
///                        for top level path, this should be an empty string
void getSubdirsRecursive(std::vector<std::string>& output, 
                         const std::string& path,
                         const std::string& prependStr)
{
    std::vector<std::string> firstLvl;
    getSubdirs(firstLvl, path);
    for (std::vector<std::string>::iterator i = firstLvl.begin(); 
         i != firstLvl.end(); ++i)
    {
        output.push_back(prependStr + *i);
        getSubdirsRecursive(output, 
            path + std::string("\\") + *i + std::string("\\"),
            prependStr + *i + std::string("\\"));
    }
}
Run Code Online (Sandbox Code Playgroud)


Kar*_*ari 5

2022年起使用

std::filesystem::directory_iterator
Run Code Online (Sandbox Code Playgroud)

例如:

#include <filesystem>
using namespace std::filesystem;

path sandbox = "sandbox";
create_directories(sandbox/"dir1"/"dir2");

// directory_iterator can be iterated using a range-for loop
for (auto const& dir_entry : directory_iterator{sandbox}){
    if(dir_entry.is_directory()){ //checking if dir or file.
       std::cout << dir_entry << '\n';
    }
}
Run Code Online (Sandbox Code Playgroud)

请记住,还有

std::filesystem::recursive_directory_iterator
Run Code Online (Sandbox Code Playgroud)

它用于一次性遍历嵌套子目录。

https://en.cppreference.com/w/cpp/filesystem/directory_iterator