Click here to Skip to main content
Click here to Skip to main content

Read and Write Text Files in Unicode through CStdioFile

, 7 Sep 2013
Rate this:
Please Sign up or sign in to vote.
How to read and write text files in Unicode through CStdioFile in MFC

Introduction

MFC only can handle ANSI text files with CStdioFile, because it uses the default behaviour of the CRT.

Background

MFC only can handle ANSI text files 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.

Using the Code

The following example demonstrates this:

//
// For Writing
//

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

//
// For Reading
//

// Open the file with the specified encoding
FILE *fStream;
errno_t e = _tfopen_s(&fStream, _T("\test.txt"), _T("rt,ccs=UNICODE"));
if (e != 0) return; // failed..CString sRead;
CStdioFile f(fStream);  // open the file from this stream
CString sRead;
f.ReadString(sRead);
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)

For more information, see:

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

About the Author

Vijay Bisht (India)
Software Developer (Senior)
India India
No Biography provided
Follow on   Google+

Comments and Discussions

 
QuestionGreat Article! PinmemberDave Calkins21-Feb-14 8:24 
GeneralThanks for This Useful Code PinmemberHesam Gholami1-Nov-13 7:22 
QuestionRead and write UNICODE text Files with CSdtioFile PinmemberK. H. Renders21-Jul-13 21:13 
AnswerRe: Read and write UNICODE text Files with CSdtioFile PinmemberVijay Bisht (India)7-Sep-13 0:23 
Questionvery good ,it works. Pinmembercmwinner4-Dec-12 21:40 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.

| Advertise | Privacy | Mobile
Web01 | 2.8.140709.1 | Last Updated 7 Sep 2013
Article Copyright 2012 by Vijay Bisht (India)
Everything else Copyright © CodeProject, 1999-2014
Terms of Service
Layout: fixed | fluid