Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations biv343 on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Write multibyte character string under Unicode mode

Status
Not open for further replies.

kshea

Technical User
May 31, 2002
60
CA
Hi, All:

I'm wondering if it is possible to write multibyte character strings to a file in project with build configuration of Unicode.

I have tried to write a few lines into a text file, but there exists extra bytes in the end of the string.

Any advice will be greatly appreciated.

Kay
 
I'm assuming you are using the fstream classes in the STL here.

You need to be using a locale that supports multibyte strings. Alberto Barbati has submitted libraries to the Boost project to do this. In his words, it "can read and write UTF-8, UTF-16 and UTF-32 with all endianness variants." You can get it meanwhile at
I use his older library which "has only UTF-8 and UCS-2 (which is similar to UTF-16 but lacks proper handling of surrogates and non-characters)." This is available at You'll find that there are a few modifications that need to be made to get it to work with VC++, but it is short and can be included with any project. To imbue your fstream class with a UCS2 locale, you can include the following before opening the file:

filename.rdbuf()->pubimbue(_ADDFAC(locale(), new ucs2_conversion()));

where filename is an fstream derived class.
 
First you need functionality to write the string as a char*. The old school method of ifstream and ofstream use this so this is a possiblity. Then you need to convert the string from wide char to single byte. For this you can

#inlcude <atlconv.h>


void write(LPCTSTR str)
{
USES_CONVERSION;
std::eek:fstream outputFile(&quot;output.txt&quot;);
outputFile<<T2A(str)<<endl;

}


Matt
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top