要使用 Qt 打开并按行读取一个 .txt 文件,可以使用 QFile 和 QTextStream 类来实现。下面是一个简单的示例代码:

#include <QCoreApplication>
#include <QFile>
#include <QTextStream>

int main(int argc, char *argv[])
{
    QCoreApplication a(argc, argv);

    // 打开文件
    QFile file('path/to/your/file.txt');
    if (!file.open(QIODevice::ReadOnly | QIODevice::Text))
    {
        qDebug() << 'Failed to open the file';
        return -1;
    }

    // 创建文本流
    QTextStream in(&file);

    // 按行读取文件内容
    while (!in.atEnd())
    {
        QString line = in.readLine();
        qDebug() << line;
    }

    // 关闭文件
    file.close();

    return a.exec();
}

请将上述代码中的'path/to/your/file.txt'替换为你要打开的 .txt 文件的路径。这段代码将逐行读取文件内容并将每行输出到控制台。你可以根据需要使用读取到的行进行处理。


原文地址: http://www.cveoy.top/t/topic/pkzB 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录