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

在C++中获取当前工作目录,常用的方法有两种:传统的getcwd函数和C++17引入的std::filesystem::current_path。两者都能实现目标,但在使用方式、跨平台兼容性和代码风格上有明显区别。
getcwd来自C标准库(<unistd.h></unistd.h> 在Linux/macOS,<direct.h></direct.h> 在Windows),用于获取当前工作目录的绝对路径。
特点:
char*
_getcwd
#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 directory\n";
}
return 0;
}
C++17起,<filesystem></filesystem>头文件提供了std::filesystem::current_path(),返回std::filesystem::path对象,使用更安全、直观。
立即学习“C++免费学习笔记(深入)”;
优点:
std::string或path类型,便于拼接、比较等操作#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仅返回原始字符串getcwd
current_path可能抛异常,需try-catch;getcwd通过返回值判断错误新项目建议优先使用std::filesystem::current_path(),更安全且符合现代C++风格。老旧项目或对标准版本有限制时,可继续使用getcwd,但注意边界检查。
基本上就这些。
以上就是C++如何获取当前工作目录_C++ getcwd与filesystem current_path对比的详细内容,更多请关注php中文网其它相关文章!
每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号