c++ - FindFirstFile 的预期输入类型是什么?

标签 c++ visual-studio-2010 qt unicode

首先我会说我对宽字符串和 Unicode 支持基本上一无所知。我让 QString 和 QFile 为我处理 99% 的时间,但我正在尝试编译其他人为 VC6 编写的库。

当我在 Qt Creator 中使用 MSVC2010 进行编译时出现此错误:

error: C2664: 'FindFirstFileW' : cannot convert parameter 1 from 'const char *' to 'LPCWSTR'
Types pointed to are unrelated; conversion requires reinterpret_cast, C-style cast or function-style cast

该代码使用了 FindFirstFile 函数,根据您是否使用 Unicode 字符集进行编译,该函数会被重载(某种程度上)。当 FindFirstFileA 和 FindFirstFileW 的输入似乎是两种完全不同的类型时,我不明白 FindFirstFile 需要什么类型。

所以这是我的问题:FindFirstFile 的预期输入类型是什么?

推论:如何获取 const char* 类型的文件名并将其放入 FindFirstType 可接受的格式中?

最佳答案

FindFirstFile 是一个定义如下的宏:

#ifdef UNICODE
#define FindFirstFile  FindFirstFileW
#else
#define FindFirstFile  FindFirstFileA
#endif // !UNICODE

这意味着它扩展为带有 W 的那个使用 UNICODE 编译时已定义,它扩展为带有 A 的那个否则。

现在,FindFirstFile的第一个参数是 LPCSTRLPWCSTR . LPCSTRconst char* 的类型定义同时LPWCSTRconst wchar_t* 的类型定义.在您的错误消息中,您尝试传递一种类型 const char*作为 FindFirstFileW 的第一个参数它采用 const wchar_t* 类型的参数,因此出现错误。

为了使类型匹配,您需要传递类型为 const wchar_t* 的对象,你有几个选择:

std::wstring path1 = L"..."; // 1
const wchar_t* path2 = L"..."; // 2
wchar_t path3[] = L"..."; // 3

WIN32_FIND_DATA  w32fd;
FindFirstFile(path1.c_str(), &w32fd); // 1
FindFirstFile(path2, &w32fd); // 2
FindFirstFile(path3, &w32fd); // 3
FindFirstFile(L"...", &w32fd);

How do I take a filename of type const char* and put it into a form that FindFirstType will accept?

如果您的文件名仅包含基本 ASCII 字符集中的字符,那么您可以将其转换为 std::wstring像下面这样:std::wstring path(std::begin(filename), std::end(filename)); .否则,您需要使用 MultiByteToWideCharmany of the options shown here .另一种选择是调用 FindFirstFileA直接,但如果你在 Windows 上,通常使用 wchar_t 会更好开始。

关于c++ - FindFirstFile 的预期输入类型是什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17534946/

相关文章:

C++:以下代码有什么问题吗?

c++ - Visual Studio C++ 2010 错误 LNK2019 : unresolved external symbol

wpf - 绑定(bind)表达式错误的异常

qt - 使用 QImage 和 OpenCV 显示图像

c++ - 按值返回堆栈中的对象

c++ - 如何使用算术生成预处理器定义?

.net - 具有多个部署的 VS2010 数据库项目

asp.net - Paypal Integration 后处理信息

c++ - QSignalMapper 和原始 Sender()

c++ - 如何在 QT 中停止 qThread