Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to change the current working directory?

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?

like image 556
abuv Avatar asked Dec 24 '14 03:12

abuv


2 Answers

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"
like image 180
lpapp Avatar answered Sep 16 '22 23:09

lpapp


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.

like image 26
R Sahu Avatar answered Sep 18 '22 23:09

R Sahu