推荐使用std::filesystem::current_path。它安全、跨平台、易用,支持现代C++字符串操作;而getcwd需手动管理缓冲区,易出错,适用于旧项目或C++17以下环境。
在C++中获取当前工作目录,常用的方法有两种:传统的getcwd函数和C++17引入的std::filesystem::current_path。两者都能实现目标,但在使用方式、跨平台兼容性和代码风格上有明显区别。
getcwd来自C标准库( 在Linux/macOS, 在Windows),用于获取当前工作目录的绝对路径。
特点:
char*
_getcwd
#include// Linux/macOS #include // Windows #include #include 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 directory\n"; } return 0; }
C++17起,头文件提供了std::filesystem::current_path(),返回std::filesystem::path对象,使用更安全、直观。
优点:
std::string或path类型,便于拼接、比较等操作#include# include
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仅返回原始字符串getcwd
current_path可能抛异常,需try-catch;getcwd通过返回值判断错误新项目建议优先使用std::filesystem::current_path(),更安全且符合现代C++风格。老旧项目或对标准版本有限制时,可继续使用getcwd,但注意边界检查。
基本上就这些。