简体   繁体   English

在Qt中打开和读取文件

[英]Opening and reading a file in Qt

I am trying to use the menu bar to open a file (hardcoded) when 'File|Open' is clicked. 单击“文件|打开”时,我试图使用菜单栏打开文件(硬编码)。 The file should append to and display each line. 该文件应追加并显示每一行。 My function is not finding the file. 我的功能是找不到文件。 So after I click open I am getting back 'trace.txt cannot be found'. 因此,在我单击“打开”后,我回到“找不到trace.txt”的位置。 I have the file saved in the same directory as the rest of the project files. 我将文件与其余项目文件保存在同一目录中。 I am wondering if I haven't opened the file properly? 我想知道我是否没有正确打开文件? Can anyone have a look at my code and see if you're catching an error that I am not? 谁能看看我的代码,看看是否遇到了我不是的错误?

void MainWindow::readFile(){
    infoLabel->setText(tr("Invoked <b>File|Open</b>"));
    QString filename="trace.txt";
    QFile file(filename);
    if(!file.exists()){
        qDebug() << "File <i>cannot</i> be found "<<filename;
    }else{
        qDebug() << filename<<" Opening...";
    }
    QString line;
    textEdit->clear();
    if (file.open(QIODevice::ReadOnly | QIODevice::Text)){
        QTextStream stream(&file);
        while (!stream.atEnd()){
            line = stream.readLine();
            textEdit->setText(textEdit->toPlainText()+"0x"+line+"\n");
            qDebug() << "line: "<<line;
        }
    }
    file.close();
}

UPDATE: I changed the QFile object to the direct path and that found the file. 更新:我将QFile对象更改为直接路径,并找到了文件。 On the other hand, I am reading it in an infinite loop, which never makes it to the textEdit and continually outputs to the debugger. 另一方面,我正在无限循环中读取它,它永远不会进入textEdit并持续输出到调试器。 Any ideas? 有任何想法吗?

Use current or currentPath() to see with which directory you are working. 使用current或currentPath()查看您正在使用哪个目录。 See this example to understand the current directory: 请参见以下示例以了解当前目录:

QFile file;
QDir::setCurrent("/tmp");
file.setFileName("readme.txt");
QDir::setCurrent("/home");
file.open(QIODevice::ReadOnly);      // opens "/home/readme.txt" under Unix

From http://doc.qt.io/qt-5/qfile.html#QFile 来自http://doc.qt.io/qt-5/qfile.html#QFile

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM