如何更改当前工作目录? [英] How to change the current working directory?

查看:414
本文介绍了如何更改当前工作目录?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在开发一个程序,该程序从某个目录中提取文件并将其复制到Qt的工作目录中,以供我的应用程序读取.现在,我当前的路径是:

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

/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?

推荐答案

将其复制到Qt的工作目录

copies it to the working directory of Qt

不知道您所说的"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.

但是为什么要完全更改工作目录?尽管您可能想解决一个问题,但您可能会立即引入其他问题.感觉就像是 XY问题.我认为您在实践中将需要其他解决方案,例如上述解决方案.

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:

布尔QDir :: setCurrent(const QString& path)

将应用程序的当前工作目录设置为path.如果目录已成功更改,则返回true;否则,返回false.否则返回false.

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:

#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

构建并运行

qmake && make && ./main

输出

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

这篇关于如何更改当前工作目录?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆