How to read UTF-8 text from file using Qt?

Maciej Ziarko picture Maciej Ziarko · Apr 12, 2011 · Viewed 17k times · Source

I have some problems with reading UTF-8 encoded text from file. My version reads only ASCII characters.

#include <QtCore>

int main()
{
    QFile file("s.txt");

    if (!file.open(QIODevice::ReadOnly | QIODevice::Text))
    {
        return -1;
    }

    QTextStream in(&file);
    while(!in.atEnd())
    {
        QString line = in.readLine();
        qDebug() << line;
    }
}

s.txt:

jąkać się
ślimak
śnieżyca

output:

"jka si" 
"limak" 
"nieyca"

What should I use?

Answer

John Flatness picture John Flatness · Apr 12, 2011

See QTextStream::setCodec():

in.setCodec("UTF-8");