FindFirstFile总是返回无效句柄
问题描述:
我的目标是列出文本文件在特定的目录中并让用户加载其中一个文件。FindFirstFile总是返回无效句柄
我使用Windows,在我的编译器中预定义了Unicode。
问:FileHandle总是有INVALID_HANDLE_VALUE。这是什么原因,我该如何纠正?
我最后的代码如下所示:
ListAllTxtFiles(L"C:\\Users\\Tnc\Desktop\\Yazılım Çalışmaları\\Projects\\Oyun Projem\\data\\SaveFiles\\");
void ListAllTxtFiles(const wchar_t *Directory)
{
TCHAR Buffer[2048];
wsprintf(Buffer, L"s%*.txt", Directory);//there are security considerations about this function
WIN32_FIND_DATAW FindData;
HANDLE FileHandle = FindFirstFileW(Buffer, &FindData);
if (FileHandle == INVALID_HANDLE_VALUE)
{
printf("Could not find any files..\n");
}
else
{
do
{
printf("Found %s\\%s\n", Directory, FindData.cFileName);
} while (FindNextFile(FileHandle, &FindData));
CloseHandle(FileHandle);
}
}
您是否尝试过从['GetLastError'](https://msdn.microsoft.com/en-us/library/windows/desktop/ms679360%28v=vs.85%29.aspx)打印结果? –
'GetLastError'会为你解答这个问题。最有可能的路径是不正确的。 –
约翰已经回答了你的问题。 'wsprintf()'中的格式字符串格式错误,导致'Buffer'接收错误的数据,所以'FindFirstFileW()'失败。注意,你直接使用'FindFirstFileW()',因此'Buffer'应该被声明为'WCHAR'而不是'TCHAR','wsprintf()'应该是'wsprintfW()'。由于'cFileName'是'WIN32_FIND_DATAW'中的'WCHAR []',要将它打印为Unicode字符串,则需要使用'wprintf()'而不是'printf()',或者至少使用'%ls在'printf()'中代替'%s'。 –