Qt how to open a file in the current directory? or what's wrong with that?

I am trying to open an xml file in the current location of the executable

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

        if(!file.open(QIODevice::ReadOnly))
        {
            insertItem("IO ERR");
        }
  • When I run it from the creator of Qt, everything works. currentPath()returns the path to the executable folder

  • When I go to the folder project-build-desktop/and try to start it manually currentPath()returns/home/user/Documents

EDIT

also tried with the same results:

Qt::current().path();
Qt::current().absolutePath();
+5
source share
4 answers

Try using QCoreApplication :: applicationDirPath () instead of QDir :: currentPath ().

See http://doc.qt.io/qt-5/qcoreapplication.html#applicationDirPath for details

+8
source

QDir::currentPath(). , Qt Creator, , (*.pro). , .

Edit

Linux. / QDir:

  • QDir:: (). ()
  • QDir:: (). AbsolutePath()

.

+2

, QFile

Linux-,

#include <QtCore>

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

. /TestQFile, test.xml, .

UPDATE: , , , , , :

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

2: QtCreator . , QDir:: currentPath(), QtCreator.

+2

, . , ( ) Resource System.

/config ( settings.xml). - . . , QFile file(":/config/settings.xml") . QT- 2.0.1 QT 4.7 Windows.

+1

All Articles