我正在使用下面的代码
#include "stdafx.h"
#include <iostream>
#include "stdafx.h"
#include <windows.h>
#include <string>
#include <commdlg.h>
#include <Shlwapi.h>
#pragma comment (lib, "Shlwapi.lib")
// This function is an abomination -- I just wrote it to be quick.
std::wstring CombinePaths(std::wstring const &pattern, LPCWSTR filename) {
std::wstring tmp(pattern);
tmp.push_back('\0');
PathRemoveFileSpec(&tmp[0]);
std::wstring retVal(MAX_PATH, '\0');
PathCombine(&retVal[0], tmp.c_str(), filename);
return retVal.c_str();
}
void FindFiles(std::wstring const &pattern) {
WIN32_FIND_DATA fd;
HANDLE h = FindFirstFile(pattern.c_str(), &fd);
if (h == INVALID_HANDLE_VALUE) {
wprintf(L"FindFirstFile. Err=%d\n", GetLastError());
return;
}
do {
std::wstring fullPath = CombinePaths(pattern, fd.cFileName);
wprintf(L"FullPath=%s\n", fullPath.c_str());
} while (FindNextFile(h, &fd));
FindClose(h);
}
int main()
{
FindFiles(L"c:\\Windows"); //Passes
FindFiles(L"c:\\"); //Fails
std::cin.get();
return 0;
}
为什么它不通过 C:\\
?有什么建议吗?
最佳答案
来自FindFirstFile()
文档:
HANDLE WINAPI FindFirstFile( _In_ LPCTSTR lpFileName, _Out_ LPWIN32_FIND_DATA lpFindFileData );
Parameters
lpFileName [in]
The directory or path, and the file name. The file name can include wildcard characters, for example, an asterisk (*) or a question mark (?).
This parameter should not be NULL, an invalid string (for example, an empty string or a string that is missing the terminating null character), or end in a trailing backslash ().
(强调我的)
这意味着您根本无法将 C:\
作为参数传递并期望它起作用。
也就是说,您不应该使用 FindFirstFile()
来检查目录是否存在。这有点像用 12 号口径的霰弹 Gunicorn 死一只蚊子:它有效,但杀伤力太大了。
GetFileAttributes()
是您应该使用的功能。
关于c++ - 驱动器号上的 FindFiles 失败但通过路径,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50417907/