How to change the current working directory?

僤鯓⒐⒋嵵緔 提交于 2019-12-10 15:06:51

问题


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?


回答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"



回答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.



来源:https://stackoverflow.com/questions/27630879/how-to-change-the-current-working-directory

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!