How to change the current working directory?

13,860

Solution 1

copies it to the working directory of Qt

Not sure what exactly you mean by "Qt" in this context. If it is where the library is installed, you should associate that path with the file name then to be processed rather than setting the current working directory to be fair.

But why do you want to change the working directory at all? While you may want to solve one problem with it, you might instantly introduce a whole set of others. It feels like the XY problem. I think you will need a different solution in practice, like for instance the aforementioned.

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

bool QDir::​setCurrent(const QString & path)

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

Therefore, you would 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"

Solution 2

QDir has a function, setCurrent, for that purpose.

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

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

Share:
13,860
abuv
Author by

abuv

Software Dev C++ &amp; C Bash Batch Objective-C White Hat

Updated on June 15, 2022

Comments

  • abuv
    abuv almost 2 years

    I am working on a program that takes a file from a certain directory and copies it to the working directory of Qt to be read by my application. 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 with:

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

    My question is, how would I go about changing this path?

  • László Papp
    László Papp over 9 years
    This is wrong documentation as the OP uses 5.4, not ancient 4.8. It is probably not an issue in this case, but it is a bad practice.
  • abuv
    abuv over 9 years
    You are right, I fell into the XY problem. My issue was resolved with @Tay2510. What I needed to do was change the build directory specified in Projects->Run Settings->Working Directory.
  • Guilherme Nascimento
    Guilherme Nascimento over 7 years
    An excellent answer, which is not just a link, but is a great explanation and still has a working example. Congratulations! (Many answers here on the site are just links or have just typed "try this")