c++kquote>C++中获取当前工作目录推荐使用C++17的std::filesystem::current_path(),跨平台且简洁;2. Windows可用GetCurrentDirectoryA,Linux/Unix可用getcwd,需处理错误返回。

在C++中获取当前工作目录,常用的方法依赖于操作系统和标准库的支持。不同平台下的实现略有差异,但可以通过标准或系统API来完成。
使用 std::filesystem(C++17 及以上)
从 C++17 开始,std::filesystem 提供了跨平台的方式来操作文件系统,包括获取当前工作目录。
示例代码:
#include #includeint main() {std::string cwd = std::filesystem::current_path().string();std::cout << "当前工作目录: " << cwd << std::endl;return 0;}
编译时需启用 C++17 支持,例如使用 g++:
立即学习“C++免费学习笔记(深入)”;
g++ -std=c++17 main.cpp -o main
Windows 平台使用 GetCurrentDirectory
在 Windows 系统中,可以调用 Win32 API 中的 GetCurrentDirectory 函数。
#include #include #includeint main() {const DWORD size = 256;std::vector buffer(size);DWORD result = GetCurrentDirectoryA(size, buffer.data());if (result != 0) {std::cout << "当前工作目录: " << buffer.data() << std::endl;}return 0;}
注意链接 kernel32.lib(通常自动包含)。
Linux/Unix 使用 getcwd
在类 Unix 系统中,可使用 POSIX 函数 getcwd 获取当前目录。
#include #include #includeint main() {const size_t size = 256;std::vector buffer(size);char* result = getcwd(buffer.data(), size);if (result) {std::cout << "当前工作目录: " << buffer.data() << std::endl;}return 0;}
函数成功返回指向缓冲区的指针,失败返回 nullptr。
基本上就这些方法。推荐优先使用 std::filesystem::current_path(),简洁且跨平台。如果项目不支持 C++17,则根据系统选择对应 API。注意处理异常或错误返回值,避免程序崩溃。
以上就是C++如何获取当前工作目录_C++ 当前工作目录获取方法的详细内容,更多请关注创想鸟其它相关文章!
版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。
如发现本站有涉嫌抄袭侵权/违法违规的内容, 请发送邮件至 chuangxiangniao@163.com 举报,一经查实,本站将立刻删除。
发布者:程序猿,转转请注明出处:https://www.chuangxiangniao.com/p/1477691.html
微信扫一扫
支付宝扫一扫