C 中的 Readline 函数输出奇怪的结果
我正在尝试使用 GNU Readline 库在 shell 中实现自动完成和历史记录。我使用 fgets()
来检索用户,在阅读了 readline
函数的工作原理后,我决定使用它来支持自动完成等。但是当我执行在我的程序中,在我键入任何输入之前,readline
函数会在 shell 上输出奇怪的字符。奇怪的结果,例如 P�6
、PJ�
`、
P�#、
P�s`。由于某种原因,它总是以 P 开头。这是我的代码:
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);
}
}
关于问题是什么有什么想法吗?谢谢。
I'm trying to implement auto completion and history in my shell using the GNU Readline library. I was using fgets()
to retrieve user and after reading on how the readline
function works, I decide on using it so as to support auto completion etc. But when I execute my program, the readline
function outputs weird characters on the shell before I even type any input. Weird results like P�6
, PJ�
`,
P�#,
P�s`. For some reason it always start with P. Here's my code:
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);
}
}
Any ideas as to what the problem is? Thanks.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
在将
userInput
传递给readLine()
之前对其进行初始化:这是传递给
readLine()
函数的参数的描述(我在此处找到userInput
): a href="http://unixhelp.ed.ac.uk/CGI/man-cgi?readline+3" rel="nofollow">man readline):如果参数为 NULL 或空字符串,不发出任何提示。
由于您尚未初始化
userInput
它正在显示其中发生的任何内容。Initialise
userInput
before passing it toreadLine()
:This is the description for argument passed to the
readLine()
function (which I found here man readline):If the argument is NULL or the empty string, no prompt is issued.
As you had not initialised
userInput
it was displaying whatever happened to be in there.