如何使用 C++ 列出 Windows 中的子目录?使用可以跨平台运行的代码会更好。
原文由 avee 发布,翻译遵循 CC BY-SA 4.0 许可协议
如何使用 C++ 列出 Windows 中的子目录?使用可以跨平台运行的代码会更好。
原文由 avee 发布,翻译遵循 CC BY-SA 4.0 许可协议
这是我的问题解决方案,虽然它是 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("\\"));
}
}
原文由 avee 发布,翻译遵循 CC BY-SA 4.0 许可协议
3 回答2k 阅读✓ 已解决
2 回答3.9k 阅读✓ 已解决
2 回答3.2k 阅读✓ 已解决
1 回答3.2k 阅读✓ 已解决
1 回答2.7k 阅读✓ 已解决
3 回答3.4k 阅读
1 回答1.6k 阅读✓ 已解决
http://msdn.microsoft.com/en-us/library/aa364418(v=vs.85).aspx
和
http://msdn.microsoft.com/en-us/library/aa365200(v=vs.85).aspx
它在 windows vista/7 或 xp 之间的跨平台:P