【问题标题】:Implementing history in own shell C++在自己的 shell C++ 中实现历史
【发布时间】:2015-04-12 01:27:01
【问题描述】:

我正在我自己的 shell 中用 C++ 实现历史命令。我正在用 NonCanonicalMode 编写它。我已经实现了向上箭头键和向下箭头键以及退格键。我不知道如何开始历史。我应该使用其中一个 C++ 库中的内置函数吗?

----编辑

字符 *buf;

rl_bind_key('\t',rl_abort);//disable auto-complete

while((buf = readline("\n >> "))!=NULL)
{
    if (strcmp(buf,"quit")==0)
        break;

    printf("[%s]\n",buf);

    if (buf[0]!=0)
        add_history(buf);
}

【问题讨论】:

  • 你可以窃取 libreadline 中的代码吗?
  • C++ 标准库中没有这方面的内容。 C++ 标准库甚至不支持非规范输入模式。您需要使用第三方库或自己编写,使用操作系统的 API。
  • 如果我自己尝试实现它会怎样...我有这样的东西(检查编辑)

标签: c++ shell unix


【解决方案1】:

我没有使用过NonCanonicalMode,但这是我在我的一个项目中实现 readline 历史记录的方式。

也许对你有用:

#include <string>
#include <memory>
#include <iostream>
#include <algorithm>

#include <readline/readline.h>
#include <readline/history.h>

// clean up user input by deleting spaces from each end
inline std::string& trim(std::string& s, const char* t = " \t")
{
    s.erase(s.find_last_not_of(t) + 1);
    s.erase(0, s.find_first_not_of(t));
    return s;
}

// smart pointer to clean up memory
// allocated by readline

struct malloc_deleter
{
    template <class T>
    void operator()(T* p) { std::free(p); }
};

typedef std::unique_ptr<char, malloc_deleter> cstring_uptr;

int main()
{
    // this directory needs to exist beforehand
    const std::string config_dir = "/home/wibble/.prog";

    using_history();
    read_history((config_dir + "/.history").c_str());

    std::string shell_prompt = "> ";

    cstring_uptr input;
    std::string line, prev;

    input.reset(readline(shell_prompt.c_str()));

    // copy input into a std::string
    while(input && trim(line = input.get()) != "exit")
    {
        if(!line.empty())
        {
            // only add line to history if it is different
            // from previous line
            if(line != prev)
            {
                add_history(line.c_str());
                write_history((config_dir + "/.history").c_str());
                prev = line;
            }

            // process the input
            std::reverse(line.begin(), line.end());

            // give relevant output
            std::cout << "reply: " << line << '\n';

        }
        input.reset(readline(shell_prompt.c_str()));
    }
}

我不喜欢我需要在两个地方调用readline(),但我不知道如何重新编写循环以避免它。也许我错过了一些简单的东西?

它使用带有自定义删除器的智能指针std::unique_ptr 来清理readline 使用malloc() 分配的缓冲区。

【讨论】:

    猜你喜欢
    • 2015-12-18
    • 1970-01-01
    • 1970-01-01
    • 2021-02-07
    • 1970-01-01
    • 2010-12-02
    • 2017-09-30
    • 2015-01-11
    • 2015-11-02
    相关资源
    最近更新 更多