如何使用CreateFile()API函数打开名为.txt的文件?

hkB*_*sai 2 string unicode winapi filenames createfile

某些Unicode字符(如)的代码点消耗超过2个字节.如何使用CreateFile()与这些字符一样的Win32 API函数?

WINBASE.H

WINBASEAPI
__out
HANDLE
WINAPI
CreateFileA(
    __in     LPCSTR lpFileName,
    __in     DWORD dwDesiredAccess,
    __in     DWORD dwShareMode,
    __in_opt LPSECURITY_ATTRIBUTES lpSecurityAttributes,
    __in     DWORD dwCreationDisposition,
    __in     DWORD dwFlagsAndAttributes,
    __in_opt HANDLE hTemplateFile
    );
WINBASEAPI
__out
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
#else
#define CreateFile  CreateFileA
#endif // !UNICODE
Run Code Online (Sandbox Code Playgroud)

LPCSTR和LPCWSTR在WinNT.h中定义为:

typedef __nullterminated CONST CHAR *LPCSTR, *PCSTR;
typedef __nullterminated CONST WCHAR *LPCWSTR, *PCWSTR;
Run Code Online (Sandbox Code Playgroud)

CHARWCHARWinNT.h中定义为:

typedef char CHAR;
#ifndef _MAC
typedef wchar_t WCHAR;    // wc,   16-bit UNICODE character
#else
// some Macintosh compilers don't define wchar_t in a convenient location, or define it as a char
typedef unsigned short WCHAR;    // wc,   16-bit UNICODE character
#endif
Run Code Online (Sandbox Code Playgroud)

CreateFileA()接受LPCSTR文件名,char内部存储在8位数组中.
CreateFileW()接受LPCWSTR文件名,wchar_t内部存储在16位数组中.

我在位置C:\ .txt中创建了一个文件.看起来无法使用打开此文件CreateFile(),因为它包含Unicode代码点为0x24B62的字符,即使在WCHAR数组单元格中也不适合.

但该文件存在于我的硬盘中,Windows正常管理它.如何通过Win32 API函数打开此文件,就像Windows内部一样?

Dav*_*nan 7

这些字符由UTF-16代理对表示.它需要两个宽字符元素来表示该代码点.所以,你只需要打电话CreateFile通过必要的代理对.当然,你需要使用广泛的变体CreateFile.

据推测,您不会在代码中对这样的文件名进行硬编码.在这种情况下,您将从文件对话框FindFirstFile等获取它.这些API将为您提供适当的UTF-16编码缓冲区.