开发者

using readline() to edit commands, in c

开发者 https://www.devze.com 2023-03-31 23:19 出处:网络
i have to implement a few CLI features and now I am try开发者_JAVA技巧ing to use readline() so that the user can edit or go through their commands. Its working so far in that it allows the user to ent

i have to implement a few CLI features and now I am try开发者_JAVA技巧ing to use readline() so that the user can edit or go through their commands. Its working so far in that it allows the user to enter their commands and scroll through the history. Its when the user tries to edit the command. The cursor somehow manages to pass the command and go into the prompt eg "desktop r1234|5$: ls" where "desktop r12345(sp)$: " is the prompt showing working directory & root dir; and "|" is the cursor. The cursor should stop in-between '$' and 'ls' ie "desktop r12345$:| ls" .The showWrkngDir() method just displays a prompt just like a normal terminal.

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

    showWrkngDir();
    static char *line_read = (char *)NULL;
    using_history();
    rl_readline_name = basename(argv[0]);
    if (line_read)
    {
            free (line_read);
            line_read = (char *)NULL;
    }

    while(strcmp((line_read = readline ("")) , "EXIT") != 0)
    {
            if (line_read && *line_read)
                    add_history (line_read);

            tokenize(line_read);
            showWrkngDir();
    }

    return 0;
}


void showWrkngDir()
{
    char curDir[MAX_COMMAND_SZ];
    char *env;

    getcwd(curDir, sizeof(curDir));
    env = (char *)getenv("USER");

    printf("%s ",basename(curDir));

    printf("%s(sp)$ ", env);
}


I'm fairly sure that readline wants to display the prompt itself, because sometimes it needs to erase the entire screen line and redraw it from scratch. This happens especially when browsing through history, but also when editing a command that spills over to the next line, or when ^L is pressed.

Give your prompt as the argument to readline(),


Pass the prompt to readline and let it print it rather than printing it yourself using printf.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号