codec of QTextStream

If you use QTextStream to read and write files, sooner or later, you will encounter the codec problem. Interestingly, Qt uses utf-8 string almost anywhere but QTextStream does not use utf-8 codec by default. In fact QTextStream uses a codec called locale codec to read/write files. You can use the static function QTextCodec::codecForLocale() to get the locale codec on your system.

UseĀ  QTextCodec::codecForLocale()->name().constData() to get the name of the locale codec. It is the same as

textstream.codec() ->name().constData() by default.

Knowing this, you can understand why it would be problematic to store utf-8 string to a file. To correctly save utf-8 strings to a file, you should set the utf-8 codec for the textstream first:

textstream.setCodec(“UTF-8″);

After doing this, the output file will be utf-8 encoded(without a BOM).

Posted in

Comments are closed, but trackbacks and pingbacks are open.