假设我有一个文件夹,在这个文件夹中存在一些文件和文件夹,我想访问文件夹而不是文件。我怎么做。我知道在 c++ 中存在这个函数:FindFirstFileA
并且我编写了以下代码,但这适用于文件。
WIN32_FIND_DATAA ffd;
string s = "E:\\OpenCV\\SABT\\Old";
HANDLE hFind = FindFirstFileA(s.c_str(), &ffd);
if (INVALID_HANDLE_VALUE == hFind)
{
printf("no file found");
return -1;
}
if (ffd.dwFileAttributes == FILE_ATTRIBUTE_DIRECTORY)
{
do
{
std::string fn = path + ffd.cFileName;
printf("file %s\n", fn.c_str());
} while (FindNextFileA(hFind, &ffd) != 0);
}
最佳答案
您正在以错误的方式检查 ffd.dwFileAttributes
。它是一个位掩码,一个目录一次可以有多个属性,所以你需要使用&
按位与运算符而不是==
相等运算符。
在枚举子文件夹时,不要忘记也检查/忽略 "."
和 ".."
条目。并在完成枚举后调用 FindClose()
。
尝试更像这样的东西:
WIN32_FIND_DATAA ffd;
string path = "E:\\OpenCV\\SABT\\Old\\";
HANDLE hFind = FindFirstFileA((path + "*.*").c_str(), &ffd);
if (INVALID_HANDLE_VALUE == hFind)
{
if (GetLastError() == ERROR_FILE_NOT_FOUND)
printf("no folders found\n");
else
printf("error searching for folders\n");
return -1;
}
do
{
if (ffd.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY)
{
if ((lstrcmpA(ffd.cFileName, ".") != 0) &&
(lstrcmpA(ffd.cFileName, "..") != 0))
{
std::string fn = path + ffd.cFileName;
printf("%s\n", fn.c_str());
}
}
}
while (FindNextFileA(hFind, &ffd));
if (GetLastError() != ERROR_NO_MORE_FILES)
{
printf("error searching for folders\n");
}
FindClose(hFind);
关于c++ - 如何访问文件夹而不是 C++ 中特定文件夹中的文件?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40275783/