我使用 FindFirstFile(...)
函数编写了查找文件的程序。但是当我尝试打印这个函数的输出时,控制台窗口中打印了几串未知字符。
我读了一些帖子,上面写着尝试使用 wcout
而不是 cout
。我试过了,但没有用。我认为,问题在于 ANSI 和 UNICODE 编码之间的差异。有人可以帮我吗?我将非常感谢任何帮助!
这是我的代码:
#include "FindFile.h"
#include <iostream>
using namespace std;
void FindFileCl::Execute(Input * input, Response * response )
{
WIN32_FIND_DATAA FindFileData;
HANDLE h = FindFirstFileA((input->FileName).c_str(), // name of the file
&FindFileData);
if (h)
{
cout << "Search Results:\n";
cout<<(FindFileData.cFileName);
CloseHandle(h);
}
else
{
cerr << "File is NOT found:" << GetLastError() << "\n";
}
}
最佳答案
如果FindFirstFile()
失败它返回 INVALID_HANDLE_VALUE
,而不是 NULL
:
If the function fails or fails to locate files from the search string in the
lpFileName
parameter, the return value isINVALID_HANDLE_VALUE
and the contents oflpFindFileData
are indeterminate. To get extended error information, call theGetLastError
function.
和INVALID_HANDLE_VALUE
被#define
定义为-1
(以下宏位于WinBase.h):
#define INVALID_HANDLE_VALUE ((HANDLE)(LONG_PTR)-1)
意思是 if (h)
将被输入为成功或失败。在失败的情况下,cFileName
将不会被修改导致打印垃圾,因为它没有被初始化。更改 if
条件以显式检查 INVALID_HANDLE_VALUE
:
if (h != INVALID_HANDLE_VALUE)
{
}
关于C++,FindFirstFile() 的输出,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18333462/