我认为将 GNU Readline 库用于命令行提示很好,我希望我正在使用的 shell 具有该功能。现在 readline 对我有用(我的环境是 CLion、CMake、Ubuntu、BSD、C、flex-lexer 和 lemon-parser),但我还需要 flex 和 yacc 同时工作来扫描和解析输入,但代码似乎“不相容”——真的吗?
params[0] = NULL;
printf("> ");
i=1;
do {
lexCode = yylex(scanner);
/* snprintf(shell_prompt, sizeof(shell_prompt), "%s:%s $ ", getenv("USER"), getcwd(NULL, 1024));
Display prompt and read input (NB: input must be freed after use)...*/
text = strdup(yyget_text(scanner));
/*
input = readline(text);
if (!input)
break;
add_history(input);
free(input);*/
printf("lexcode %i Text %s\n", lexCode, text);
if (lexCode == 4) {
params[i++] = mystring;
if (strcmp(text, "\'\0")) {
params[i++] = mystring;
}
} else
if (lexCode != EOL) {
params[i++] = text;
printf("B%s\n", text);
}
Parse(shellParser, lexCode, text);
if (lexCode == EOL) {
dump_argv("Before exec_arguments", i, params);
exec_arguments(i, params);
corpse_collector();
Parse(shellParser, 0, NULL);
i=1;
}
} while (lexCode > 0);
if (-1 == lexCode) {
fprintf(stderr, "The scanner encountered an error.\n");
}
上面的代码具有解析和扫描功能,并注释掉了如果我同时需要两者将无法使用的 readline 功能。我能让它发挥作用吗?
最佳答案
flex+readline示例
跟随一个可以ls
和 date
的快速 flex“shell”
%{
#include <stdlib.h>
#include <readline/readline.h>
#include <readline/history.h>
#define YY_INPUT(buf,result,max_size) result = mygetinput(buf, max_size);
static int mygetinput(char *buf, int size) {
char *line;
if (feof(yyin)) return YY_NULL;
line = readline("> ");
if(!line) return YY_NULL;
if(strlen(line) > size-2){
fprintf(stderr,"input line too long\n"); return YY_NULL; }
sprintf(buf,"%s\n",line);
add_history(line);
free(line);
return strlen(buf);
}
%}
%option noyywrap
%%
ls.* system(yytext);
date.* system(yytext);
.+ fprintf(stderr, "Error: unknown comand\n");
[ \t\n]+ {}
%%
构建它:
flex mysh.fl
cc -o mysh lex.yy.c -lreadline -lfl
关于c - 如何将 GNU readline 与 flex-lexer 一起使用?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36706859/