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);
?
With ATL it's like this:
It's byte order mark (BOM) which lets Notepad know that encoding is UTF-16.
You need to pick a text encoding, convert the string to that encoding, and write the text file accordingly. Simplest is ANSI, so basically you would use the
T2CA
macro to convert yourTCHAR
string to ansi, then dump the contents in a file. Something like (untested/compiled):Because it's ANSI encoding though, it will only be readable on computers that have your same code page settings. For a more portable solution, use UTF-8 or UTF-16.
Converting to ANSI can cause problems with code pages, so it is not acceptable in many cases. Here is a function that saves unicode string to unicode text file:
Using:
Notepad understands unicode text files.
Also make sure that you write proper byte order mark in the beginning so that Notepad can read it properly.
I believe you need additional casting: