Qt how to open a file in current dir ? or what's wrong with this?

前端 未结 4 1164
遥遥无期
遥遥无期 2021-01-18 09:49

I\'m trying to open an xml file in the current location of the executable

        QString path = QDir::currentPath();
        path.append(\"/acc.xml\");
          


        
4条回答
  •  野趣味
    野趣味 (楼主)
    2021-01-18 10:15

    To open a file in the current directory, you simply call QFile constructor

    I tested this on my Linux machine and it works

    #include 
    
    int main(int argc, char** argv){
        QFile some_file("test.xml");
        if(!some_file.open(QIODevice::ReadOnly | QIODevice::Text)){
            qDebug() << "Unable to open file";
        } else {
            qDebug() << "File open successfully";
        }
        exit(-1);
    }
    

    I run ./TestQFile and if there is a test.xml in the current directory, it works.

    UPDATE: I notice that the wording of your question says that you want the file in the same directory as the executable, this can be done as follow:

    // Getting directory of the executable
    QFileInfo exec_fileinfo(argv[0]);
    qDebug() << "Executable is in" << exec_fileinfo.absolutePath();
    

    UPDATE 2: Under the project panel of QtCreator, there is a field for Working Directory. This is the directory that is returned by QDir::currentPath() if you are running it via QtCreator.

提交回复
热议问题