How do I change the current working directory?

I am working on a program that takes a file from a specific directory and copies it to the Qt working directory for my application to read. Right now, my current path is:

/Users/softwareDev/Desktop/User1/build-viewer-Desktop_Qt_5_4_0_clang_64bit-Debug/viewer.app/Conents/MacOS/viewer

To get this I used:

qDebug() << QDir::current().path();

      

and confirmed this directory:

qDebug() << QCoreApplication::applicationDirPath();

      

My question is, how do I change this path?

+3


source to share


2 answers


copies it to the Qt working directory

Not sure what exactly you mean by "Qt" in this context. If this is where the library is installed, you must associate that path with the filename and then process rather than set the current working directory.

But why do you want to change the working directory at all? While you can fix one problem with it, you can enter a whole host of others right away. It looks like an XY problem . I think you will need a different solution in practice like the one above.

If you still insist on changing the current working directory or any other reason, you can use this static method:

bool QDir :: setCurrent (const QString and path)

Sets the current working directory of the application to path. Returns true if the directory was changed successfully; otherwise it returns false.

Hence, you will be issuing something like this:

main.cpp



#include <QDir>
#include <QDebug>

int main()
{
    qDebug() << QDir::currentPath();
    if (!QDir::setCurrent(QStringLiteral("/usr/lib")))
        qDebug() << "Could not change the current working directory";
    qDebug() << QDir::currentPath();
    return 0;
}

      

main.pro

TEMPLATE = app
TARGET = main
QT = core
SOURCES += main.cpp

      

Build and run

qmake && make && ./main

      

Output

"/tmp/stackoverflow/change-cwd"
"/usr/lib"

      

+4


source


QDir

has a function for this purpose setCurrent

.

bool QDir::setCurrent ( const QString & path ) [static]

      



More details at http://doc.qt.io/qt-4.8/qdir.html#setCurrent .

+2


source







All Articles