doubt reading files with qtextstream



  • Hi normally i read the file so:

    log.setFileName(directorio.tempPath() + "/example");
                if(!log.exists())
                {
                    //no existe
                }else{
                    log.open(QFile::ReadOnly);
                    cliente.sendMessage(from,"read|@|" + log.readAll());
                    log.close();
                }
    

    But now i'm trying to read one file with text in utf-8 and at the moment i couldn't some idea how to solve it?


  • Moderators

    What does it mean you "couldn't"? The file didn't open, nothing was read or you got something else than what you got?

    readAll() reads bytes, not characters. It's your responsibility to convert the bytes to correctly encoded string, for example using QString::fromUtf8().

    EDIT Sorry, my bad. I thought you were using QFile::readAll(), but it's QTextStream::readAll() which does return a string.



  • @Chris-Kawa said in doubt reading files with qtextstream:

    QString::fromUtf8().

    one question but for utf16(i'm changed the encoding) i tried this:
    const ushort* str = read_raw(log);
    QString qstr = QString::fromUtf16(str);

    But not seem's recognize read_raw, maybe this method is only used in qt 4.8?



  • The answer is in the title of your question, use QTextStream to read the file, do not read the file directly.
    Also, since it's a textfile you shouldn't open it in binary mode. log.open(QFile::ReadOnly | QFile::Text );



  • @VRonin ok i must to put QFile::text if i put some extension like .txt. So i can't do the before example read all file and convert to utf16. ok.



  • yes, you can:

    if(log.open(QIODevice::ReadOnly | QIODevice::Text)){
    QTextStream logStream(&log);
    logStream.setCodec("UTF-8");
    logStream.setAutoDetectUnicode(true);
                    cliente.sendMessage(from,"read|@|" + logStream.readAll());
                    log.close();
    }
    

    @Jeronimo said in doubt reading files with qtextstream:

    i must to put QFile::text if i put some extension like .txt

    The extension is meaningless, it is only a trick OSs use to distinguish different files. QIODevice::Text is used to

    When reading, the end-of-line terminators are translated to '\n'. When writing, the end-of-line terminators are translated to the local encoding, for example '\r\n' for Win32.

    source http://doc.qt.io/qt-5/qiodevice.html#OpenModeFlag-enum


Log in to reply
 

Looks like your connection to Qt Forum was lost, please wait while we try to reconnect.