程序的工作目录和程序所在的目录的区别

发布时间 2023-08-09 10:05:14作者: MaxBruce

原文:https://blog.csdn.net/qq_47500842/article/details/129918472

区别
程序的工作目录指的是,该程序是被从什么目录下被启动的。在代码中一般来说./代表着在程序的工作目录下
程序所在的目录指的是,该程序在磁盘的什么目录下
实践
在Windows环境下。GetModuleFileName可以获取程序的绝对路径,即可以获取到程序的所在目录。GetCurrentDirectory可以获取到程序的工作目录

#include <QCoreApplication>
#include <QDebug>
#include <iostream>
#include <string>
#include <windows.h>
#include <QFile>
using namespace std;

void GetExeDir()
{
wstring Path;
wchar_t szModule[1024] = { 0 };
GetModuleFileName(nullptr, szModule, sizeof(szModule) / sizeof(szModule[0]));
Path = szModule;
Path.erase(Path.find_last_of(L'\\'));
std::wcout << L"exe Dir: " << Path << std::endl;
}

void getWorkingDir()
{
wchar_t szModule[1024] = {0};
GetCurrentDirectory(MAX_PATH, szModule);
std::wcout << L"working dir: " << szModule << std::endl;
}

int main(int argc, char *argv[])
{
QCoreApplication a(argc, argv);
GetExeDir();
getWorkingDir();
return a.exec();
}


我将可执行程序放在该路径下F:\QTCode\WorkDic

在F:\下打开cmd运行该程序,观察打印输出

当然在很多情况下我们都是在可执行程序所在的目录下去运行该程序。此时程序的工作目录和程序所在的目录相同

在Windows下。当一个程序运行需要另外一个DLL文件时,会在用户的机器上搜索这些动态链接库,进而加载它们。搜索的顺序依次是

程序所在的目录
程序的工作目录
系统目录 C:\Windows\system32; C:\Windows\system; C:\Windows
系统环境变量path中所列出的路径
注意
在IDE中运行程序如visual studio或者QtCreator中运行程序。往往该程序的工作目录和所在的目录是不一样的。如果需要读写文件此时应该注意.\,因为它代表的是程序的工作目录而不是程序所在的目录