C++开发POSH shell时CD命令路径拼接缺失斜杠问题如何解决
修复POSH shell cd命令路径拼接错误方案
你当前的问题是误用了std::string的append方法做路径拼接,字符串拼接不会自动补充路径分隔符/,才会出现两段路径直接连在一起的错误。你用的C++17 filesystem库本身就自带路径拼接能力,直接调用即可。
修复后完整代码
#include <filesystem> #include <string> #include <iostream> #include <cstdlib> using namespace std; namespace fs = std::filesystem; // 原全局存储当前路径的string变量,建议替换为fs::path类型专门处理路径 fs::path current_work_path = fs::current_path(); inline void cd(string cmd) { // 兼容标准shell逻辑:cd不带参数自动跳转到用户家目录 if(cmd.length() < 3) { const char* home_dir = getenv("HOME"); if(home_dir) current_work_path = fs::path(home_dir); return; } string arg = cmd.substr(3); fs::path target_path; // 判断传入路径是否为绝对路径,绝对路径直接使用不需要拼接 if(fs::path(arg).is_absolute()) { target_path = arg; } else { // fs::path的/运算符会自动处理路径分隔符,无需手动判断末尾是否带/ target_path = current_work_path / arg; } if(fs::is_directory(fs::status(target_path))) { current_work_path = target_path; } else { cout << "Error: \"" << arg << "\" is not a directory" << endl; } }
核心修改说明
- 把存储当前工作路径的变量从
std::string改为fs::path类型,专门用于路径处理,避免字符串操作带来的各类格式兼容问题 - 路径拼接改用
fs::path重载的/运算符,自动根据系统补充对应路径分隔符,无需手动判断前一段路径末尾是否带/ - 新增绝对路径判断逻辑,避免
cd /etc这类绝对路径操作出现拼接错误 - 补充cd无参数时跳转家目录的逻辑,符合常规shell的cd命令标准行为
内容的提问来源于stack exchange,提问作者Ramdomly Random
相关产品推荐
相关产品推荐

