
在C++中获取当前工作目录,常用的方法依赖于操作系统和标准库的支持。不同平台下的实现略有差异,但可以通过标准或系统API来完成。
从 C++17 开始,std::filesystem 提供了跨平台的方式来操作文件系统,包括获取当前工作目录。
示例代码:
#include <filesystem>
#include <iostream>
<p>int main() {
std::string cwd = std::filesystem::current_path().string();
std::cout << "当前工作目录: " << cwd << std::endl;
return 0;
}</p>编译时需启用 C++17 支持,例如使用 g++:
立即学习“C++免费学习笔记(深入)”;
g++ -std=c++17 main.cpp -o main在 Windows 系统中,可以调用 Win32 API 中的 GetCurrentDirectory 函数。
#include <windows.h>
#include <iostream>
#include <vector>
<p>int main() {
const DWORD size = 256;
std::vector<char> buffer(size);
DWORD result = GetCurrentDirectoryA(size, buffer.data());
if (result != 0) {
std::cout << "当前工作目录: " << buffer.data() << std::endl;
}
return 0;
}</p>注意链接 kernel32.lib(通常自动包含)。
在类 Unix 系统中,可使用 POSIX 函数 getcwd 获取当前目录。
#include <unistd.h>
#include <iostream>
#include <vector>
<p>int main() {
const size_t size = 256;
std::vector<char> buffer(size);
char* result = getcwd(buffer.data(), size);
if (result) {
std::cout << "当前工作目录: " << buffer.data() << std::endl;
}
return 0;
}</p>函数成功返回指向缓冲区的指针,失败返回 nullptr。
基本上就这些方法。推荐优先使用 std::filesystem::current_path(),简洁且跨平台。如果项目不支持 C++17,则根据系统选择对应 API。注意处理异常或错误返回值,避免程序崩溃。
以上就是C++如何获取当前工作目录_C++ 当前工作目录获取方法的详细内容,更多请关注php中文网其它相关文章!
每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号