您的位置:首页 >C++获取当前工作目录方法详解
发布于2025-10-04 阅读(0)
扫一扫,手机访问
推荐使用C++17的std::filesystem::current_path()获取当前工作目录,跨平台且简洁;2. 旧版本可用操作系统API:Windows调用GetCurrentDirectory,Linux/macOS使用getcwd;3. 编译时需启用C++17并链接-lstdc++fs库。

在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:
示例代码(跨平台兼容):
#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基本上就这些。优先推荐 std::filesystem::current_path(),现代、安全、跨平台。
下一篇:小红书关闭收藏和点赞方法
售后无忧
立即购买>office旗舰店
售后无忧
立即购买>office旗舰店
售后无忧
立即购买>office旗舰店
售后无忧
立即购买>office旗舰店
正版软件
正版软件
正版软件
正版软件
正版软件
1
2
3
7
9