
在C++中获取当前工作目录,常用的方法依赖于操作系统和标准库的支持。不同平台下的实现略有差异,但可以通过标准或系统API来完成。
使用 std::filesystem(C++17 及以上)
从 C++17 开始,std::filesystem 提供了跨平台的方式来操作文件系统,包括获取当前工作目录。
示例代码:
#include#include int main() { std::string cwd = std::filesystem::current_path().string(); std::cout << "当前工作目录: " << cwd << std::endl; return 0; }
编译时需启用 C++17 支持,例如使用 g++:
立即学习“C++免费学习笔记(深入)”;
g++ -std=c++17 main.cpp -o mainWindows 平台使用 GetCurrentDirectory
在 Windows 系统中,可以调用 Win32 API 中的 GetCurrentDirectory 函数。
#include#include #include int main() { const DWORD size = 256; std::vector
buffer(size); DWORD result = GetCurrentDirectoryA(size, buffer.data()); if (result != 0) { std::cout << "当前工作目录: " << buffer.data() << std::endl; } return 0; }
注意链接 kernel32.lib(通常自动包含)。
Linux/Unix 使用 getcwd
在类 Unix 系统中,可使用 POSIX 函数 getcwd 获取当前目录。
#include#include #include int main() { const size_t size = 256; std::vector
buffer(size); char* result = getcwd(buffer.data(), size); if (result) { std::cout << "当前工作目录: " << buffer.data() << std::endl; } return 0; }
函数成功返回指向缓冲区的指针,失败返回 nullptr。
基本上就这些方法。推荐优先使用 std::filesystem::current_path(),简洁且跨平台。如果项目不支持 C++17,则根据系统选择对应 API。注意处理异常或错误返回值,避免程序崩溃。










