如何使用 C++ 列出 Windows 中的子目录?使用可以跨平台运行的代码会更好。
这是我的问题解决方案,但它是仅限 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) != 0
&& (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("\\"));
}
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)