在VC++中用CreateFile打开一个已存在的文件,结果返回INVALID_HANDLE_VALUE,一番排查发现是路径参数问题,项目配置使用的是Unicode字符集,如果直接用CreateFile("D:\\test.zip", GENERIC_READ, FILE_SHARE_READ, NULL, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, NULL),会提示"const char *"类型的实参与"LPCWSTR"类型的形参不兼容
HANDLE h = CreateFile((LPCWSTR)"D:\\test.zip", GENERIC_READ, FILE_SHARE_READ, NULL, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, NULL);
if (h == INVALID_HANDLE_VALUE)
{
return NULL;
}
代码虽然能编译运行,文件也存在,但是返回INVALID_HANDLE_VALUE,跳转到定义发现用的CreateFileW,所以是LPCWSTR
HANDLE
WINAPI
CreateFileW(
_In_ LPCWSTR lpFileName,
_In_ DWORD dwDesiredAccess,
_In_ DWORD dwShareMode,
_In_opt_ LPSECURITY_ATTRIBUTES lpSecurityAttributes,
_In_ DWORD dwCreationDisposition,
_In_ DWORD dwFlagsAndAttributes,
_In_opt_ HANDLE hTemplateFile
);
#ifdef UNICODE
#define CreateFile CreateFileW
改为
const char* path = "D:\\test.zip";
int size1 = MultiByteToWideChar(CP_ACP, 0, path, -1, NULL, 0);
TCHAR* wpath = new TCHAR[size1];
MultiByteToWideChar(CP_ACP, 0, path, -1, wpath, size1);
HANDLE h = CreateFile(wpath, GENERIC_READ, FILE_SHARE_READ, NULL, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, NULL);
if (h == INVALID_HANDLE_VALUE)
{
return NULL;
}
就不会返回INVALID_HANDLE_VALUE,
也可以用
CreateFile(L"D:\\test.zip", GENERIC_READ, FILE_SHARE_READ, NULL, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, NULL)