C++,FindFirstFile() 的输出

标签 c++ winapi

我使用 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 is INVALID_HANDLE_VALUE and the contents of lpFindFileData are indeterminate. To get extended error information, call the GetLastError 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/

相关文章:

python - 使用 Win32 使窗口透明?

c++ - 带指针的基于范围的循环

c++ - 以下代码对于多线程增量计数器和打印是否是一个好的解决方案?

c++ - 如何使用 map vector

c++ - 如何快速混合 RGBA 无符号字节颜色?

c++ - 子类化后编辑控件无法获得焦点或设置文本

c++ - 在不同字节中写入位 c c++

windows - 如何在 Windows 中检测何时连接了新硬件?

c++ - 拖动分隔栏以调整两个面板的大小时,内容(或背景)仍然存在

winapi - RegSaveKey 返回 ERROR_PRIVILEGE_NOT_HELD