September 14, 2007

How to write Textfiles with encoding in MFC

MFC only can handle ANSI-textfiles with CStdioFile, because it uses the default behaviour of the CRT.
But you can open the file-stream by yourself and then you can use the new encoding functionality in the CRT to specify the correct encoding.

The follwing example demonstrates this:

// Old-Style... do not use... //CStdioFile f; //f.Open(_T("\test.txt"), CFile::modeCreate | CFile::modeWrite); // Open the file with the specified encoding FILE *fStream; errno_t e = _tfopen_s(&fStream, _T("\test.txt"), _T("wt,ccs=UNICODE")); if (e != 0) return; // failed.. CStdioFile f(fStream); // open the file from this stream f.WriteString(_T("Test")); f.Close();

This example will create/open the file test.txt with UNICODE-Encoding. It will also write a UNICODE (UTF-16) BOM.

The following encodings are widely used:

  • “ccs=UNICODE” => UTF-16 (Big endian)
  • “ccs=UTF-8” => UTF-8
  • “ccs=UTF-16LE” => UTFS-16LE (Little endian)
  • “ccs=ANSI” => ANSI (default encoding of the OS)

If the text file aready exists, it will try to read an existing BOM and read the file with this encoding.

For more info see:


Posted 2 months, 1 day ago on September 14, 2007
The trackback url for this post is http://blog.kalmbachnet.de/bblog/trackback.php/105/

Re: How to write Textfiles with encoding in MFC
As an addition please see: http://blog.kalmbachnet.de/?postid=107
Posted 1 month ago by Jochen Kalmbach • • • Reply
Comment Trackback URL : http://blog.kalmbachnet.de/bblog/trackback.php/105/512/

Comments have now been turned off for this post