c++ 设置和获取当前工作目录

转自:http://blog.163.com/strive_only/blog/static/89380168200910285636730/

 

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
获取当前工作目录设置指定目录当前工作目录,你可以使用C++标准库中的`<filesystem>`头文件(C++17及更高版本)或`<unistd.h>`头文件(旧版本)。 以下是两种方法的示例代码: 使用`<filesystem>`头文件(C++17及更高版本): ```cpp #include <iostream> #include <filesystem> namespace fs = std::filesystem; int main() { // 获取当前工作目录 std::string currentPath = fs::current_path().string(); std::cout << "当前工作目录:" << currentPath << std::endl; // 设置指定目录当前工作目录 std::string newDirectory = "/path/to/new/directory"; fs::current_path(newDirectory); // 再次获取当前工作目录,确认是否设置成功 currentPath = fs::current_path().string(); std::cout << "新的当前工作目录:" << currentPath << std::endl; return 0; } ``` 使用`<unistd.h>`头文件(旧版本): ```cpp #include <iostream> #include <unistd.h> int main() { // 获取当前工作目录 char currentPath[FILENAME_MAX]; if (getcwd(currentPath, sizeof(currentPath)) != nullptr) { std::cout << "当前工作目录:" << currentPath << std::endl; } else { std::cout << "无法获取当前工作目录" << std::endl; return 1; } // 设置指定目录当前工作目录 const char* newDirectory = "/path/to/new/directory"; if (chdir(newDirectory) == 0) { std::cout << "已将目录更改为:" << newDirectory << std::endl; } else { std::cout << "无法将目录更改为:" << newDirectory << std::endl; return 1; } // 再次获取当前工作目录,确认是否设置成功 if (getcwd(currentPath, sizeof(currentPath)) != nullptr) { std::cout << "新的当前工作目录:" << currentPath << std::endl; } else { std::cout << "无法获取当前工作目录" << std::endl; return 1; } return 0; } ``` 你可以根据你的编译环境和需求选择使用哪种方法。这些代码会获取当前工作目录并显示出来,然后将指定目录设置当前工作目录,再次获取当前工作目录以确认是否设置成功。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值