Using CFile::typeUnicode

2019-07-29 04:35发布

I need to be able to read/write to a file unicode strings that contain Chinese characters.

The documentation says that CFile::typeUnicode is "used in derived classes only", but I cannot find any reference to any derived class that does use it.

Is there any "official" version of CFile that will allow me to read and write unicode?

Or am I better off trying to use something like this: http://www.codeproject.com/Articles/4119/CStdioFile-derived-class-for-multibyte-and-Unicode

标签: unicode mfc
2条回答
Anthone
2楼-- · 2019-07-29 05:15

This seems to be an easier way: see How to Read and Write Text Files in Unicode through CStdioFile, it uses a FILE stream to open a file as Unicode and then opens a CStdioFile class using that stream.

//
// 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();
查看更多
戒情不戒烟
3楼-- · 2019-07-29 05:21

You can also consider using a different class that does all of the hard work for you. I use CTextFileDocument:

CTextFileDocument class help topic

You can use the provided CTextFileWrite to write to a number of Unicode flavours. Example:

//Create file. Use UTF-8 to encode the file
CTextFileWrite myfile(_T("samplefile.txt"), 
            CTextFileWrite::UTF_8 );

ASSERT(myfile.IsOpen());

//Write some text
myfile << "Using 8 bit characters as input";
myfile.WriteEndl();
myfile << L"Using 16-bit characters. The following character is alfa: \x03b1";
myfile.WriteEndl();
CString temp = _T("Using CString.");
myfile << temp;
查看更多
登录 后发表回答