c++kquote>推荐使用C++17的std::filesystem::current_path()获取当前工作目录,跨平台且简洁;2. 旧版本可用操作系统API:Windows调用GetCurrentDirectory,Linux/macOS使用getcwd;3. 编译时需启用C++17并链接-lstdc++fs库。

在C++中获取当前工作目录路径,最常用的方法是使用标准库中的 头文件,这是从 C++17 开始引入的功能。它提供了跨平台的接口来操作文件系统,包括获取当前工作目录。
使用 std::filesystem::current_path()
这是推荐的方式,简洁且跨平台(Windows、Linux、macOS 都支持)。
包含头文件 调用 std::filesystem::current_path() 函数 返回值是一个 std::filesystem::path 类型,可直接转换为字符串
示例代码:
#include #include 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++(C++17 之前)
如果不能使用 C++17,可以使用操作系统提供的 API:
立即学习“C++免费学习笔记(深入)”;
在 Windows 上使用 GetCurrentDirectory() 在 Linux/macOS 上使用 getcwd()
示例代码(跨平台兼容):
#include #include #include #ifdef _WIN32 #include #define getcwd _getcwd#else #include #endifint main() { char buffer[1024]; if (getcwd(buffer, sizeof(buffer)) != nullptr) { std::cout << "当前工作目录: " << buffer << std::endl; } else { std::cerr << "获取路径失败" << std::endl; } return 0;}
编译注意事项
使用 std::filesystem 时,注意:
编译器需支持 C++17(如 GCC 8+、Clang 7+、MSVC 2017+) 编译时添加 -std=c++17 某些系统(如 Linux)还需链接 stdc++fs 库
例如使用 g++ 编译:
g++ -std=c++17 main.cpp -lstdc++fs
基本上就这些。优先推荐 std::filesystem::current_path(),现代、安全、跨平台。
以上就是C++程序如何获取当前的工作目录路径的详细内容,更多请关注创想鸟其它相关文章!
版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。
如发现本站有涉嫌抄袭侵权/违法违规的内容, 请发送邮件至 chuangxiangniao@163.com 举报,一经查实,本站将立刻删除。
发布者:程序猿,转转请注明出处:https://www.chuangxiangniao.com/p/1473864.html
微信扫一扫
支付宝扫一扫