由于 QTextStream 的无限循环

Infinite cycle due to QTextStream

因此,我在尝试从文件中读取行(逐行)时遇到了无限循环。我试图像这样使用 do{}while(); 循环:

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

但我得到的是空字符串。

当然,我检查了文件路径(没错)。我试图使用 /Users/user/tts.txt 路径但没有更改。我试图读取其他文件(如 m3u)。它不适用于 macOS Catalina、Windows 10、Linux (Debian)。

那么,为什么我得到了无限循环?

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;
}

查看 QTextstream 文档 https://doc.qt.io/qt-5/qtextstream.html。有一个逐行阅读的例子。您的 while 循环应该读取直到流到达缓冲区的末尾,并且许多内置读取函数将 return false 当他发生时

所以,我明白了。我错误地打开了文件。

我正在使用:

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

但应该是这样的:

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