Search code examples
clinuxraspberry-pi3raspbian

Linux C console application not using previous command on "keyup"


I've got the following issue:

int main(int argc, char **argv){
    while(1){
        char command[25];
        scanf(" %25[^\n]s", command);
        printf("Command '%s'\n", command); 
    }
    return 0;
}  

Now whenever I type something in the console it prints me a message with what I just typed.
But if I use the arrow up key to get the last command out of the memory, the command being sent is

^[[A

Which results in the cursor being moved up by the program.
Now how do I fix this?
I want that the last command from memory is triggered.
Thanks in advance!


Solution

  • This is actually pretty non-trivial thing you are asking for. Luckily, there is a library to fix it: GNU Readline library. Be aware about its licensing, though. Last I heard, it's actual GPL and therefore your own program needs to be that, too, if you use it. NetBSD has a library called libedit, which seems to claim to do much of the same thing with less restrictive license.

    Here are some more help with readline: https://eli.thegreenplace.net/2016/basics-of-using-the-readline-library/

    And if you can stomach the idea of not integrating it directly into your own program, there is a handy utility program called rlwrap, which provides the end-user at least some of the goodness transparently.