我已经把之前命令的历史记录保存在一个二维数组中了。但我不知道如何检查向上箭头。
如何使用 C 编程语言实现此功能(在 Linux 中)?
最佳答案
感谢 n.m. 的好建议。
下面是libreadline
的使用示例:
// rltest.c
#include <stdio.h>
#include <stdlib.h>
#include <readline.h>
#include <history.h>
int main(void)
{
char* input, shell_prompt[100];
// Configure readline to auto-complete paths when the tab key is hit.
rl_bind_key('\t', rl_complete);
// while work is not 0 program executes the loop
int work = 1;
printf("Commands to use: name, ver, exit \n");
// loop for working with commands
while(work) {
// Build prompt string.
snprintf(shell_prompt, sizeof(shell_prompt), "your command $ ");
// Display prompt and read input
input = readline(shell_prompt);
// Check for EOF.
if (!input)
break;
// Add input to history.
add_history(input);
// Command analysis and execution
if( 0 == strcmp(input, "exit") )
{
printf("Bye!\n");
work = 0;
}
if( 0 == strcmp(input, "name") )
{
printf("I'm readline example\n");
}
if( 0 == strcmp(input, "ver") )
{
printf("My version is 0.1\n");
}
// ...
// Free input for future use
free(input);
}
return 0;
}
编译这个例子:
1) 安装readline库
apt-get install libreadline-dev
2) 编译程序为
gcc rltest.c -I/usr/include/readline -lreadline
关于c - 如何用C语言创建一个可以实现向上箭头历史捕获的shell?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28824064/