To append data to an existing file and create the file if it does not exists already, use the
CFile::modeNoTruncate
flag instead of
CFile::modeCreate
. The latter will only create files if they did not exist and throw an exception otherwise (see the
CFile Class[
^]).
The
sizeof operator - cppreference.com[
^] is processed during compilation time to get the size of an object. It will not return the length of dynamic runtime data like strings.
You have to pass the length of the data in bytes when writing:
myFile.Write(data.GetString(), data.GetLength() * sizeof(TCHAR));
GetLength()
returns the number of characters in the string. Because the
Write()
function is byte based, the number of characters has to be multiplied with the number of bytes per character (2 with Unicode applications).
Note also that you are creating a Unicode text file if your application is Unicode (what the
L
prefix of the string literal assumes).