[SOLVED]Probem reading Chinese text files
-
Hi,
I am trying to read from a txt file (in chinese) using this piece of code
@QString filename="C:/Users/danil/Documents/iwhiteboard/学科.txt";
QFile file(filename); if (!file.open(QIODevice::ReadOnly | QIODevice::Text)) { qDebug()<<"THE FILE COULD NOT BE OPENED...."; return 0; } else { qDebug()<<"IT IS OPENED AND WE CAN READ IT..."; QTextStream in(&file); while (!in.atEnd()) { QString line = in.readLine(); myString.append(line); } file.close(); in.flush(); }
@
I suspect it has something to do with codecs but everything I have tried from the doc lead me to nothing so far.The filename comes from a QFileDialog in case somebody is wondering.
Any help would be appreciated.Thanks.
-
Hi, seems the problem is in your first statement.
Anyway, please tell us:
-
which Qt are you using Qt4 /Qt5,
-
which compiler are you using MSVC or not?
-
-
Thanks for the reply,
I am using Qt 4 and MSVC.Would you care to tell what is wrong with that statement? -
You can given a try to
@
QString filename=QString::fromLocal8Bit("C:/Users/danil/Documents/iwhiteboard/学科.txt");
@AFAIK,
If you are using VS2008SP1 + KB980263 or MSVC2010 or MSVC2013, you can use utf8 as your executable character set. If you are using MSVC2005 or MSVC2010, utf8 can not be used. -
Thanks 1+1=2 ,
I was able to get this to work ,and the current solution is as follows in case somebody else faces the same problem:@
//GET THE FILE NAME FROM A QFileDialog
filenames=dialog.selectedFiles();
filename=filenames.at(0);//USE fromUtf8 ON THE filename
QByteArray byteArray = filename.toUtf8();
const char* cString = byteArray.constData();
QString codedFilename = QString::fromUtf8(cString);//THIS WAS TO SEE WHAT IT GAVE ME
testLineEdit->setText(codedFilename);
QString myString;QFile file(codedFilename);
if (!file.open(QIODevice::ReadOnly | QIODevice::Text))
{
//WE FALL HERE WHEN THE FILE FAILS TO BE OPENED
testLineEdit->setText(file.errorString());
return;
}
else
{
//AND HERE WHEN WE HAVE SUCCESSFULY OPENED IT.
testLineEdit->setText("opened");
}QTextStream in(&file); //MAKE SURE WHAT YOU READ IS UTF-8 in.setCodec("UTF-8"); while (!in.atEnd()) { QString line = in.readLine(); myString.append(line); } testLineEdit->setText(myString); file.close(); in.flush(); //NOW myString CONTAINS TEXT YOU READ.
@