2
我试图在我的shell中使用GNU Readline库实现自动完成和历史记录。我使用fgets()
来检索用户,并在阅读readline
函数的工作方式后,决定使用它来支持自动完成等。但是当我执行我的程序时,readline
函数在输入奇怪的字符之前在我甚至输入任何输入。奇怪的结果,如P�6
,PJ�
`,
P #,
P s`。出于某种原因,它总是先从P.这里是我的代码:C中的readline函数输出奇怪的结果
int main(int argc, char* argv[]) {
char *historic, userInput[1000];
static char **cmdArgv;/**The argv of the main*/
sa.sa_handler = handle_signal;
sigaction(SIGINT, &sa, NULL);
sa.sa_flags = SA_RESTART; /** Restart function incase it's interrupted by handler */
cmdArgv = malloc(sizeof (*cmdArgv));
welcomeScreen();//just printf's nothing special
while(TRUE)
{
shellPrompt();// getcwd function
historic = readline(userInput);
if (!historic)
break;
//path autocompletion when tabulation hit
rl_bind_key('\t', rl_complete);
//adding the previous input into history
add_history(historic);
if(check_syntax(userInput) == 0){
createVariable(userInput);
}
else{
tokenize(cmdArgv, userInput);
special_chars(cmdArgv);
executeCommands(cmdArgv, userInput);
}
}
任何想法的问题是什么?谢谢。
@hjmd:感谢它的工作。但为什么我必须在我的情况下memset userInput?我在readline上浏览了很多教程,而且他们都没有这样做。 – mkab
@hjmd:刚刚看到你编辑的答案。谢谢。仍然困惑我为什么没有教程提到它。 – mkab
我看到的例子使用了'sprintf()'或类似的函数来将参数填充到'readLine'中,该参数会用一个以空字符结尾的字符串填充它,并显示出合理的内容。尝试用一些东西来填充它以见证行为。例如,在'memset()'调用'userInput [0] ='$';'之后,你应该显示一个美元提示。 – hmjd