skip to Main Content

So, I get infinite cycle while trying to read lines from file (line by line). I was trying to use do{}while(); cycle like that:

QTextStream stream(stdin);
QString line;
do {
    line = stream.readLine();
} while (!line.isNull()); 

but I get empty string.

Sure, I checked file path (it is right). I was trying to use /Users/user/tts.txt path but without changes. I was trying to read other files (like m3u). And it’s not working on macOS Catalina, Windows 10, Linux (Debian).

So, why did I get infinite cycle?

QStringList Manager::GetLinesFromFile(const QString &nameOfFile)
{
    QStringList lines = {};

    //path to file
    const QString path = QCoreApplication::applicationDirPath() + "/bin/" + "tts.txt";
    //"/Users/user/tts.txt"

    QFile buffer;
    buffer.QFile::setFileName(path);

    #ifndef Q_DEBUG
    qDebug() << path;
    #endif

    if(buffer.QFile::exists())
    {
        if(!buffer.QIODevice::open(QIODevice::ReadOnly))
        {
            #ifndef Q_DEBUG
            qCritical() << "error: can't open file";
            #endif
        }
        else
        {
            QTextStream stream(&buffer);

             // both conditions
            // (!stream.QTextStream::atEnd()) 
            while(!buffer.QFileDevice::atEnd())
                lines.QList::push_back(stream.QTextStream::readLine());

            buffer.QFile::close();
        }
    }
    else
    {
        #ifndef Q_DEBUG
        qCritical() << "error: file not exists";
        #endif
    }

    return lines;
}

2

Answers


  1. Chosen as BEST ANSWER

    So, I got it. I opened the file incorrectly.

    I was using:

    if(!file.QIODevice::open(QIODevice::ReadOnly))

    but it should be like that:

    if(!file.QFile::open(QFile::ReadOnly))


  2. Have a look at the QTextstream documentation https://doc.qt.io/qt-5/qtextstream.html. There is an example of reading line by line. Your while loop should read until the stream reaches the end of the buffer and many of the in built read functions will return false when his happens

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search