• Uncategorized

About c : Proper-use-of-readline-in-order-to-display-history

Question Detail

I’m making a program that shoul act like a real terminal in linux (ubuntu).

What I have is this:

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

   char cmd[500];

       printf("$ > ");
       fgets(cmd, 499, stdin);
   }while(strcmp(cmd, "exit\n") != 0);

   return 0;

What I want to do is: When I press the up key, it should show me what I typed before, and so on… If I press the up key 3 times, it should show me the 3rd latest command used, and so on for the bottom key.

I am not that good with C, but I understood that there is a library readline, and a history one, but I don’t know how to use them in order to accomplish this.

Thanks in advance

Question Answer

Consider using the GNU readline library (mixing both editable readline feature and history feature). It has documentation for the Readline itself and for the history sub-library.

You’ll use readline function to read the line, and add_history to add some “accepted” line into the history list. You might also want to customize the completer.

Spend a couple of hours to read the documentation, it is quite well explained with code samples.

(the readline library is GPL licensed, and is commonly available on Linux. E.g. on Debian install the libreadline6-dev package; I don’t know if readline works on Windows.)

You probably should not explicitly use (in your program) signal(7)-s with readline. If you do, dive into the documentation and the source code.

You might want to consider ncurses library instead. It enables you to code full-screen terminal applications (like vim or emacs are).

Of course, readline and ncurses want the input to be a pseudo-tty (so it cannot be a pipe or a file). Read the tty demystified page to understand more the gory details, and see termios(3)!

If you want a graphical user interface, dive into GTK or Qt. If you want a web interface, you’ll need some HTTP server library like libonion or Wt (and a lot of knowledge about web related technologies: HTML5, CSS, Javascript, Jquery, AJAX, … see w3schools – which is imperfect).

You may also like...

Leave a Reply

Your email address will not be published.

This site uses Akismet to reduce spam. Learn how your comment data is processed.