在自己的外壳C++中实现历史记录
Implementing history in own shell C++
我正在自己的shell中实现历史命令,C++。我正在非规范模式下编写它。我已经实现了向上箭头键和向下箭头键以及退格键。我不知道如何开始历史。我应该使用C++库中的内置函数吗?
----编辑
夏亚 *布夫;
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);
}
我没有使用过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()
分配的缓冲区。
相关文章:
- 如果没有malloc,链表实现将失败
- 如何在c++中实现处理器调度模拟器
- 如何在c++中使用引用实现类似python的行为
- 实现无开销push_back的最佳方法是什么
- 使用简单类型列表实现的指数编译时间.为什么
- 如何在BST的这个简单递归实现中消除警告
- 实现一个在集合上迭代的模板函数
- 我应该实现右值推送功能吗?我应该使用std::move吗
- 如何正确实现和访问运算符的各种自定义枚举器
- C++Union/Struct位域的实现和可移植性
- 这个极客对极客的trie实现是否存在内存泄漏问题
- 在c++中实现LinkedList时,应出现未处理的错误
- 为左值和右值的包装器实现C++范围
- 使用模板进行堆栈实现; "name followed by :: must be a class or namespace"
- 使用GSoap实现ONVIF
- 在用于格式4的arm模拟器中实现功能时的一个问题
- 用于AVX的ln(x)的实现,m256
- 用常见虚拟函数实现的任意组合来实现派生类的正确方法是什么
- 在C++中,如何在类和函数(可能是模板化的)的头中编写完整的实现
- 在自己的外壳C++中实现历史记录