使用WriteFile API将unicode CString写入文件

Hay*_*tuk 1 winapi atl cstring writefile

如何使用WriteFile Win32 API函数将CString实例的内容写入CreateFile打开的文件?

请注意不使用MFC,包含"atlstr.h"使用CString

编辑:我可以

WriteFile(handle, cstr, cstr.GetLength(), &dwWritten, NULL); 
Run Code Online (Sandbox Code Playgroud)

要么

WriteFile(handle, cstr, cstr.GetLength() * sizeof(TCHAR), &dwWritten, NULL); 
Run Code Online (Sandbox Code Playgroud)

Rom*_* R. 5

使用ATL就是这样的:

CString sValue;
CStringW sValueW(sValue); // NOTE: CT2CW() can be used instead

CAtlFile File;
ATLENSURE_SUCCEEDED(File.Create(sPath, GENERIC_WRITE, ...));
static const BYTE g_pnByteOrderMark[] = { 0xFF, 0xFE }; // UTF-16, Little Endian
ATLENSURE_SUCCEEDED(File.Write(g_pnByteOrderMark, sizeof g_pnByteOrderMark));
ATLENSURE_SUCCEEDED(File.Write(sValueW, (DWORD) (sValueW.GetLength() * sizeof (WCHAR))));
Run Code Online (Sandbox Code Playgroud)

这是字节顺序标记(BOM),它让记事本知道编码是UTF-16.