2011-12-01 88 views
2

我試圖在我的shell中使用GNU Readline庫實現自動完成和歷史記錄。我使用fgets()來檢索用戶,並在閱讀readline函數的工作方式後,決定使用它來支持自動完成等。但是當我執行我的程序時,readline函數在輸入奇怪的字符之前在我甚至輸入任何輸入。奇怪的結果,如P�6PJ�`,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); 
    } 
} 

任何想法的問題是什麼?謝謝。

回答

3

初始化userInput傳遞之前readLine()

memset(userInput, 0, sizeof(userInput)); 

這是傳遞給readLine()函數參數的說明(我發現這裏man readline):

如果參數爲空或空字符串,不會發出提示。

由於您還沒有初始化userInput它顯示了發生在那裏的任何事情。

+0

@hjmd:感謝它的工作。但爲什麼我必須在我的情況下memset userInput?我在readline上瀏覽了很多教程,而且他們都沒有這樣做。 – mkab

+0

@hjmd:剛剛看到你編輯的答案。謝謝。仍然困惑我爲什麼沒有教程提到它。 – mkab

+0

我看到的例子使用了'sprintf()'或類似的函數來將參數填充到'readLine'中,該參數會用一個以空字符結尾的字符串填充它,並顯示出合理的內容。嘗試用一些東西來填充它以見證行爲。例如,在'memset()'調用'userInput [0] ='$';'之後,你應該顯示一個美元提示。 – hmjd