
在C++中获取当前工作目录路径,最常用的方法是使用标准库中的 <filesystem> 头文件,这是从 C++17 开始引入的功能。它提供了跨平台的接口来操作文件系统,包括获取当前工作目录。
这是推荐的方式,简洁且跨平台(Windows、Linux、macOS 都支持)。
示例代码:
#include <iostream>
#include <filesystem>
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++17,可以使用操作系统提供的 API:
立即学习“C++免费学习笔记(深入)”;
示例代码(跨平台兼容):
#include <iostream>
#include <cstdlib>
#include <cstring>
#ifdef _WIN32
#include <direct.h>
#define getcwd _getcwd
#else
#include <unistd.h>
#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 时,注意:
例如使用 g++ 编译:
g++ -std=c++17 main.cpp -lstdc++fs
以上就是C++程序如何获取当前的工作目录路径的详细内容,更多请关注php中文网其它相关文章!
每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号