C++ 如何获取 Qt 应用程序的当前工作目录路径?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/17646700/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to get current working directory path of a Qt application?
提问by Tan Viet
I'm writing a program in C++ using the Qt library. I would like to get current working directory of my program. I found the QDir::currentPath()and QCoreApplication::applicationDirPath()function but they give back the directory where the application executable is. I don't wanna get the directory that contains the application executable.
我正在使用 Qt 库用 C++ 编写程序。我想获取我程序的当前工作目录。我找到了QDir::currentPath()和QCoreApplication::applicationDirPath()函数,但它们返回了应用程序可执行文件所在的目录。我不想获取包含应用程序可执行文件的目录。
I have uploaded the image which describes the path that I want to get.
我已经上传了描述我想要获取的路径的图像。
Does anyone has any solutions?
有没有人有任何解决方案?
Thank you!
谢谢!
回答by user1810087
Your application cannot know where the project is, because this is a qt-creator option. If you want to run your binary in the project path you have to setup your working directory insideqt-creator to the correct path. Then QDir::currentPath()
will return the path you want to have.
您的应用程序无法知道项目在哪里,因为这是一个 qt-creator 选项。如果你想在项目路径运行的二进制文件,你必须设置你的工作目录内QT-创建者的正确路径。然后QDir::currentPath()
将返回您想要的路径。
goto: projects->[environment]->run->working directory
转到:项目->[环境]->运行->工作目录
回答by ted
Checkout QCoreApplication::applicationDirPath(), it tries to figure out the directory the executable is in, rather than checking the current working directory
Checkout QCoreApplication::applicationDirPath(),它试图找出可执行文件所在的目录,而不是检查当前的工作目录
回答by pixelgrease
The source code directory is available via qmake
variables and can "defined" for access within C++ source files:
源代码目录可通过qmake
变量获得,并且可以“定义”以在 C++ 源文件中访问:
# Demo.pro:
# set PROJECT_PATH to the "project path" with a trailing slash
DEFINES += PROJECT_PATH=\"\\"$${_PRO_FILE_PWD_}/\\"\"
// mainwindow.cpp
qDebug() << "Able to find main.cpp?..."
<< QFile::exists(PROJECT_PATH "main.cpp"));
Output:
输出:
Able to find main.cpp?... true