PDA

View Full Version : Read unicode text from file



Boron
24th October 2012, 14:12
Hello,

I have a text file that is encoded in some "Unicode format". I do not know which Unicode this might be (in fact I don't know anything about Unicode at all, to be honest).
When I open this file in my editor (the old Crimson Editor under WinXP) I have to manually set the encoding type to "Unicode Encoding". Only then I can read the file content.

What I really want to do is to read the file content in a Qt based application.
The following code prints only one cryptic line. The line looks like *â– 2.
QFile logFile("C:\\cl.txt");
logFile.open( QIODevice::ReadOnly );
QString line = logFile.readLine();
while( !logFile.atEnd() ) {
qout << line; // qout is a QTextStream working on stdout
line = logFile.readLine();
}
The file does not contain special characters. The whole file content could easily be treated as pure ASCII text. But it is in some Unicode encoding.
How can I read the file content?

Lesiok
24th October 2012, 14:26
Read about QTextStream especially QTextStream::setAutoDetectUnicode and QTextStream::setCodec

Boron
24th October 2012, 15:27
Thank you, the setAutoDetectUnicode(true) seemed to be the solution.
For those who should ever have a comparable problem, the following code did it:
FILE* fp = fopen( logFile.fileName().toAscii(), "r" );
QTextStream in(fp, QIODevice::ReadOnly);
in.setAutoDetectUnicode(true);

QString line;
do
{
if( line.contains(QString("[REPORT]")))
{
qout << line << endl;
}
line = in.readLine();
} while (!line.isNull());