gpt4 book ai didi

c++ - 如何更改当前工作目录?

转载 作者:可可西里 更新时间:2023-11-01 04:25:06 25 4
gpt4 key购买 nike

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

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

为此,我使用了:

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

并确认此目录:

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

我的问题是,我将如何改变这条路径?

最佳答案

copies it to the working directory of Qt

不确定在这种情况下您所说的“Qt”到底是什么意思。如果它是库的安装位置,您应该将该路径与文件名相关联然后进行处理,而不是将当前工作目录设置为公平。

但是为什么要更改工作目录呢?虽然您可能想用它解决一个问题,但您可能会立即引入一整套其他问题。感觉就像XY problem .我认为您在实践中将需要不同的解决方案,例如上述。

如果您仍然坚持更改当前工作目录或其他原因,您可以使用这个静态方法:

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.

因此,您将发布如下内容:

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;
}

主程序

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

构建并运行

qmake && make && ./main

输出

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

关于c++ - 如何更改当前工作目录?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27630879/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com