C++命令行中的CD命令

CD Command in C++ command line

我正在尝试为 shell 创建一个 CD 命令,我称之为 POSH(Pine 自己的 shell)。

如果前面的 cd 命令没有以 / 结尾,它将追加两个路径并抛出 (cd pine 然后 cd src 会出错,因为路径将是 /home/dingus/pinesrc 而不是 /home/dingus/pine/src).

我知道为什么会这样,但似乎无法解决。

这里是源代码:

inline void cd(string cmd)
{
    if(cmd.length() < 3) return;
    string arg = cmd.substr(3);
    if(fs::is_directory(fs::status( string(path).append(arg))))
    {
        path.append(arg);
    }
    else cout << "Error: \"" << arg << "\" is not a directory" << endl;
}

string(path).append(arg) 正在执行字符串连接。您没有在文件系统元素之间附加任何您自己的斜杠。所以,如果 path/home/dingus/,那么 cd pine 只会将 pine 追加到生成 /home/dingus/pine 的末尾,然后 cd src 只会追加src 到最后生成 /home/dingus/pinesrc,如您所见。

您需要做更多类似的事情:

string curr_path;

inline void cd(string cmd)
{
    if (cmd.length() < 4) return;
    string arg = cmd.substr(3);
    string new_path = curr_path;
    if ((!new_path.empty()) && (new_path.back() != '\')) {
        new_path += '\';
    }
    new_path += arg;
    if (fs::is_directory(fs::status(new_path))) {
        curr_path = new_path;
    }
    else {
        cout << "Error: \"" << arg << "\" is not a directory" << endl;
    }
}

但是,既然你正在使用 <filesystem> 库,你应该使用 std::filesystem::path(特别是因为 std::filesystem::status() 只接受 std::filesystem::path 开始)。让库为您处理任何路径连接,例如:

fs::path curr_path;

inline void cd(string cmd)
{
    if (cmd.length() < 4) return;
    string arg = cmd.substr(3);
    fs::path new_path = curr_path / arg;
    if (fs::is_directory(new_path)) {
        curr_path = new_path;
    }
    else {
        cout << "Error: \"" << arg << "\" is not a directory" << endl;
    }
}

std::filesystem::path 实现 operator/ 插入斜线(如果斜线不存在)。