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

标签 string winapi unicode filenames createfile

一些 Unicode 字符(如𤭢)的代码点占用超过 2 个字节。如何对这些字符使用 Win32 API 函数,如 CreateFile()

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

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

typedef __nullterminated CONST CHAR *LPCSTR, *PCSTR;
typedef __nullterminated CONST WCHAR *LPCWSTR, *PCWSTR;

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

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

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

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

最佳答案

这样的字符用UTF-16 surrogate pairs表示.它需要两个宽字符元素来表示该代码点。因此,您只需调用 CreateFile 并传递必要的代理对。当然,您需要使用 CreateFile 的广泛变体。

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

关于string - 如何使用 CreateFile() API 函数打开名为 𤭢.txt 的文件?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12644150/

相关文章:

java - 我希望我的程序在用户输入整数以外的任何内容时显示错误消息并将其循环回来

python - 从列表中的每个项目中提取整数和 unicode

python - HTMLParser.HTMLParser().unescape() 不起作用

java - 获取Java语言的unicode字符

PHP 和 MySQLi 将查询结果转换为字符串时出错

java - 使用 StringTokenizer 和 String.split( ) 的区别?

c# - 在 B4A 中获取两个字符串之间的精确字符串

c++ - 纹理未通过 glGenerateMipmap() 加载

c - 向子进程发送信号时出现问题

c++ - 如何从powerbuilder11.5调用win32 dll?