
在C++中获取当前工作目录路径,最常用的方法是使用标准库中的
使用 std::filesystem::current_path()
这是推荐的方式,简洁且跨平台(Windows、Linux、macOS 都支持)。
- 包含头文件
- 调用 std::filesystem::current_path() 函数
- 返回值是一个 std::filesystem::path 类型,可直接转换为字符串
示例代码:
#include#include int main() { try { std::string cwd = std::filesystem::current_path().string(); std::cout << "当前工作目录: " << cwd << std::endl; } catch (const std::exception& e) { std::cerr << "获取路径失败: " << e.what() << std::endl; } return 0; }
兼容旧版本 C++(C++17 之前)
如果不能使用 C++17,可以使用操作系统提供的 API:
立即学习“C++免费学习笔记(深入)”;
- 在 Windows 上使用 GetCurrentDirectory()
- 在 Linux/macOS 上使用 getcwd()
示例代码(跨平台兼容):
#include#include #include #ifdef _WIN32 #include #define getcwd _getcwd #else #include #endif int main() { char buffer[1024]; if (getcwd(buffer, sizeof(buffer)) != nullptr) { std::cout << "当前工作目录: " << buffer << std::endl; } else { std::cerr << "获取路径失败" << std::endl; } return 0; }
编译注意事项
使用 std::filesystem 时,注意:
- 编译器需支持 C++17(如 GCC 8+、Clang 7+、MSVC 2017+)
- 编译时添加 -std=c++17
- 某些系统(如 Linux)还需链接 stdc++fs 库
例如使用 g++ 编译:
g++ -std=c++17 main.cpp -lstdc++fs基本上就这些。优先推荐 std::filesystem::current_path(),现代、安全、跨平台。










