在C++开发中,获取当前工作目录是一项基础但常用的操作。程序运行时的工作目录不一定是可执行文件所在目录,而是启动该程序时所在的 shell 路径,因此明确获取方式有助于正确处理相对路径。

使用 POSIX 标准函数 getcwd
在 Linux 或 macOS 等类 Unix 系统中,可以使用 <unistd.h> 中的 getcwd 函数获取当前工作目录。该函数将绝对路径写入用户提供的缓冲区。
#include <iostream>
#include <unistd.h>
#include <cstdlib>
int main() {
char buffer[1024];
// 获取当前工作目录,存入 buffer
if (getcwd(buffer, sizeof(buffer)) != NULL) {
std::cout << "当前工作目录: " << buffer << std::endl;
} else {
perror("getcwd 失败");
return 1;
}
return 0;
}
使用 Windows API
在 Windows 平台,可以调用 Kernel32 提供的 GetCurrentDirectory 函数,需要包含 <windows.h>。
#include <iostream>
#include <windows.h>
int main() {
char buffer[MAX_PATH];
// 获取当前工作目录,MAX_PATH 为系统定义最大路径长度
DWORD len = GetCurrentDirectory(MAX_PATH, buffer);
if (len > 0) {
std::cout << "当前工作目录: " << buffer << std::endl;
} else {
std::cout << "获取目录失败" << std::endl;
}
return 0;
}
使用 C++17 std::filesystem
C++17 引入了文件系统库,使用 std::filesystem::current_path() 可以跨平台获取工作目录,推荐在新项目中使用。
#include <iostream>
#include <filesystem>
int main() {
// 跨平台获取当前工作目录
std::filesystem::path cwd = std::filesystem::current_path();
std::cout << "当前工作目录: " << cwd.string() << std::endl;
return 0;
}
几种方式对比
| 方式 | 平台 | 需包含头文件 |
|---|---|---|
| getcwd | Unix-like | <unistd.h> |
| GetCurrentDirectory | Windows | <windows.h> |
| std::filesystem::current_path | 跨平台 | <filesystem> |
小结
如果项目已经支持 C++17,优先使用 std::filesystem::current_path,代码简洁且无需处理平台差异。老旧环境再根据对应系统调用选择合适的接口即可。