1

I am writing a C program on Linux platform where I need to show something on console instantly when the up or down arrow key is pressed without ^[[A or ^[[B getting written on the console and then pressing enter to show something on the console.

I am simulating linux shell and I want to impelement linux shell like history feature where when we press up and down key, recent entered commands are displayed. I am using GNU history library to implement this. How do I do that?

  • 1
    ncurses, maybe? but this is too broad, nonetheless. – Sourav Ghosh Feb 02 '18 at 07:42
  • 2
    For what platform? "Instantly" implies your program is always waiting for the input. Is that true? – Retired Ninja Feb 02 '18 at 07:43
  • @RetiredNinja when I press up arrow key "^[[A" is getting printed on the console and then it waits to press enter key to show something on console. I want to print something on cosole as soon as I press up arrow key without ^[[A getting printed on console. – Akhilesh Yadav Feb 02 '18 at 07:50
  • 1
    You'll need to look into the `termios` interface in POSIX, or use the `ncurses` library which handles the majority of the issues for you already (including identifying which characters are generated by the up-arrow key based on your terminal type, as documented by `$TERM`). You might find some of the information in [How to distinguish between ESCAPE and escape sequence?](https://stackoverflow.com/questions/48039759/) useful. You might also find some useful information in [Canonical vs non-canonical terminal input](https://stackoverflow.com/questions/358342/). – Jonathan Leffler Feb 02 '18 at 07:57
  • [Here](https://stackoverflow.com/a/75499310/6013016) is the answer. – Scott Feb 19 '23 at 14:12

1 Answers1

1

we can write our own function for get char like disable echo flag ,read character and again enable the echo flag .So that you can see the print on console.

#include <stdio.h>
#include <unistd.h>
#include <termios.h>

int getch();

int main(int argc, char **argv) {
   int ch;
   for (;;) {
      ch = getch();
      if(ch == 27)
         printf("UP arrow\n");
      else if(ch ==28)
         printf("down arrow\n");
      else
         printf("wrong input \n");

      break;
   }
   return 0;
}

int getch() {
   struct termios oldtc;
   struct termios newtc;
   int ch;
   tcgetattr(STDIN_FILENO, &oldtc);
   newtc = oldtc;
   newtc.c_lflag &= ~(ICANON | ECHO);
   tcsetattr(STDIN_FILENO, TCSANOW, &newtc);
   ch=getchar();
   tcsetattr(STDIN_FILENO, TCSANOW, &oldtc);
   return ch;
}
Rahul
  • 68
  • 1
  • 7
  • Why have you used ch==27 and ch==28 for up and down arrow key? I used printf to display the value of up and down arrow key using your program and it's showing 27 for both keypress; ascii value for up and down key are 38 and 40 respectiviely. – Akhilesh Yadav Feb 02 '18 at 09:08