Write a unicode CString to a file using WriteFile API

Hayri Uğur Koltuk picture Hayri Uğur Koltuk · Sep 21, 2011 · Viewed 8k times · Source

How can I write contents of a CString instance to a file opened by CreateFile using WriteFile Win32 API function?

Please note MFC is not used, and CString is used by including "atlstr.h"

edit: Can just I do

WriteFile(handle, cstr, cstr.GetLength(), &dwWritten, NULL); 

or

WriteFile(handle, cstr, cstr.GetLength() * sizeof(TCHAR), &dwWritten, NULL); 

?

Answer

Roman R. picture Roman R. · Sep 21, 2011

With ATL it's like this:

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))));

It's byte order mark (BOM) which lets Notepad know that encoding is UTF-16.