[Qt-interest] Non-latin characters in QString and char * on Windows

Thiago Macieira thiago at kde.org
Wed Mar 2 23:14:22 CET 2011


On Wednesday, 2 de March de 2011 23:05:25 Konstantin Tokarev wrote:
> Hi all,
> 
> I need to convert QString, containg non-latin characters (specifically,
> cyrillic) to const char *, in order to open file with ifstream (requirement
> of 3rd party library). One may think that it's about
> QString::toLocal8Bit(), but it does not help on Windows!

It does, but you have to write proper code to get it.

You've been caught in a simple mistake that happens to many people:
    const char * fileNameStr = fileName.toLocal8Bit().constData();

Ask yourself: who owns this pointer that you got? Is it the QString? If it is, 
can you point me to any method in QString that return a const char * in the 
local 8-bit encoding?

The answer is that the QByteArray owns it.

Which QByteArray you may ask? THAT is the problem. When you figure out where 
the QByteArray is, you'll have solved the problem.

Anyway, the recommended way to encode a filename from QString to 8-bit is to 
use QFile::encodeName.

> See attached program. On Linux with UTF-8 everything works fine with either
> toUtf8 or toLocal8Bit. On Windows (default encoding is CP1251) both
> functions return crap (different between each other). Of course, ifstream
> cannot open corrupted file paths.
> 
> How to get proper representation of QString fileName in const char * ?
-- 
Thiago Macieira - thiago (AT) macieira.info - thiago (AT) kde.org
  Senior Product Manager - Nokia, Qt Development Frameworks
      PGP/GPG: 0x6EF45358; fingerprint:
      E067 918B B660 DBD1 105C  966C 33F5 F005 6EF4 5358
-------------- next part --------------
A non-text attachment was scrubbed...
Name: not available
Type: application/pgp-signature
Size: 190 bytes
Desc: This is a digitally signed message part.
Url : http://lists.qt-project.org/pipermail/qt-interest-old/attachments/20110303/6448150e/attachment.bin 


More information about the Qt-interest-old mailing list