推荐使用std::Filesystem::current_path。它安全、跨平台、易用,支持现代c++字符串操作;而getcwd需手动管理缓冲区,易出错,适用于旧项目或C++17以下环境。

在C++中获取当前工作目录,常用的方法有两种:传统的getcwd函数和C++17引入的std::filesystem::current_path。两者都能实现目标,但在使用方式、跨平台兼容性和代码风格上有明显区别。
getcwd:C风格的传统方法
getcwd来自C标准库(<unistd.h></unistd.h> 在linux/macOS,<direct.h></direct.h> 在windows),用于获取当前工作目录的绝对路径。
特点:
示例代码:
#include <unistd.h> // Linux/macos #include <direct.h> // Windows #include <iostream> #include <cstdlib> <p>int main() { char buffer[1024]; char* dir = getcwd(buffer, sizeof(buffer)); if (dir) { std::cout << "Current dir: " << dir << 'n'; } else { std::cerr << "Failed to get current directoryn"; } return 0; }
filesystem::current_path:现代C++推荐方式
C++17起,<filesystem></filesystem>头文件提供了std::filesystem::current_path(),返回std::filesystem::path对象,使用更安全、直观。
立即学习“C++免费学习笔记(深入)”;
优点:
示例代码:
#include <filesystem> #include <iostream> <p>int main() { try { auto path = std::filesystem::current_path(); std::cout << "Current dir: " << path.string() << 'n'; } catch (const std::exception& e) { std::cerr << "Error: " << e.what() << 'n'; } return 0; }
对比总结与选择建议
两种方式的核心差异在于编程范式和安全性。
- 安全性:
current_path避免了缓冲区溢出风险,getcwd需谨慎设置缓冲区大小 - 易用性:
filesystem提供丰富的路径操作API,getcwd仅返回原始字符串 - 兼容性:若项目未启用C++17或以上,只能使用
getcwd - 异常处理:
current_path可能抛异常,需try-catch;getcwd通过返回值判断错误
新项目建议优先使用std::filesystem::current_path(),更安全且符合现代C++风格。老旧项目或对标准版本有限制时,可继续使用getcwd,但注意边界检查。
基本上就这些。