Проблема завершения Readline - PullRequest
       6

Проблема завершения Readline

0 голосов
/ 31 августа 2011

Я пытаюсь заставить выполнение команды работать, но кажется, что оно не работает должным образом .. Пожалуйста, посмотрите на мой код и скажите, как я могу это исправить ..

Заранее спасибо ...

char store_commands() {
        char *newEnv;
        DIR * dir;
        char *new ;          
        struct dirent * entry;
        char *env = getenv("PATH");

        do { 
                newEnv = strsep(&env, ":");

                if(newEnv != NULL) 
                        if(strlen(newEnv) > 0) {

                                dir = opendir(newEnv);
                                if( dir == NULL ) break;
                                if(flag == 1) {
                                        flag = 0;
                                        while((entry = readdir(dir)) != NULL) {
                                                new = malloc(strlen(entry->d_name) + 1) ;  
                                                new = strcpy(new, entry->d_name);

                                                commands[++count] = new;  // add possible commands into an array
                                                printf("---%i %s\n", count ,commands[count]);
                                        }
                                }
                                closedir(dir); // close directory
                        }
        } while(newEnv);

        return **commands;
}




static char** my_completion( const char * text , int start,  int end){
        char **matches;
        store_commands();

        matches = (char **)NULL;

        if (start == 0)
                matches = rl_completion_matches ((char*)text, &my_generator);


        return matches;

}

char * dupstr (char* s) {
        char *r;

        r = (char*) malloc ((strlen (s) + 1));
        strcpy (r, s);
        return (r);
}


char* my_generator(const char* text, int state) {
        int index, len;
        char *comm;
        if (!state) {
                index = 0;
                len = (int)strlen (text);
        }



        while ( (comm = commands[index])) {
                index++;

                if (strncmp (comm, text, len) == 0)
                        return (dupstr(comm));
        }


        return NULL;
}







int main (int argc,  char * argv[]) {

        char  *command;
        using_history();
        rl_readline_name = basename(argv[0]);
        rl_attempted_completion_function = my_completion;





        while ( (command = readline(" $ "))!= NULL ) {  // scan stdin  

                rl_bind_key('\t',rl_complete);

                if(strlen(command) > 0) 
                        add_history(command);


        }


        return 0;
}


Some test cases
l (tab)
Display all 1281 possibilities? (y or n) // all possibilities come up when I put one letter *** all possibilities wrong actually what I meant was all commands including the ones dont start with l

ls (tab)
ls        lsbom     lsdistcc  lsm       lso       lsvfs  // seems alright here

however if I press enter 

comm[0]: 'ls' and comm[1]: '(null)'  // execution of the command fails!!!  WHY????
Execution of the command is failed
: No such file or directory

Если я использую статический массив, подобный этому char *test[7] = {"ls","cat","lso", "mk", "mkd", "mkdir",""}; все выглядит нормально, включая выполнение команды ..

1 Ответ

0 голосов
/ 31 августа 2011

Где находятся определения / объявления для команд [] и count?

Также: ваш стиль непоследователен, программа едва читаема. Почему вы приводите возврат из malloc () в одном месте, а не в другом?

Если (x == 0) {} и if (! X) {} эквивалентны. Сделайте свой выбор и придерживайтесь его.

Гадкий до {...} while (...); цикл может быть заменен на цикл for (...; ...; ...) {}, сохраняя два уровня отступа.

...