推荐使用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),用于获取当前工作目录的绝对路径。
特点:
- 需要手动管理缓冲区大小,容易出错
- 返回的是字符数组指针,类型为
char* - 不支持现代C++的字符串操作习惯
- 在Windows上需使用
_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;
}
登录后复制
filesystem::current_path:现代C++推荐方式
C++17起,<filesystem></filesystem>头文件提供了std::filesystem::current_path(),返回std::filesystem::path对象,使用更安全、直观。
立即学习“C++免费学习笔记(深入)”;
标签: c++ 当前目录 linux windows mac ai ios macos win stream 区别 cos 标准
还木有评论哦,快来抢沙发吧~