0

i have a C code which preforms some linux commands i need use upper arrow key in order get previous input so far the commands works fine but i failed to use upper arrow key to get previous commands (upper arrow key each time i press will get previous command and so on) how to do it ?

    while (!feof(stdin)) { 
    

        fputs (prompt, stdout);
        fflush(stdout);
        if (fgets(lbuf, BUF, stdin )) { 


            arg = args;
            *arg++ = strtok(lbuf,"\n\t");   
 
            if (args[0]) {

                if (!strcmp(args[0],"exit")) {   
                    break;
                }
else if(!strcmp(args[0],"ls")) { system("ls"); }
else if (!strcmp(args[0],"help")) { system("bash -c help"); }
else if (!strcmp(args[0],"dir")){   strcpy( command, "dir" ); system(command); }
else if (!strcmp(args[0],"whoami")){   char username[MAX_USERID_LENGTH];  cuserid(username);  printf("%s\n", username); }
else if (!strcmp(args[0],"clear")){  system("@cls||clear"); }
 else {  printf("command not found \n");                }
           }
        }
    }
    return 0; 
}
Black Snow
  • 247
  • 2
  • 14
  • 1
    *i failed*. In what way did you fail? There does not appear to be any attempt to implement the desired result in the code shown. Can you please show what you tried and/or describe more specifically what prevents you from writing the code - is it problems with the algorithm? Don't know how to read up key? Don't know how to store the history? What specifically? – kaylum Dec 07 '20 at 19:46
  • 2
    Use the `readline` library, it has built-in history support. – Barmar Dec 07 '20 at 19:49
  • 1
    https://stackoverflow.com/questions/5431941/why-is-while-feof-file-always-wrong – William Pursell Dec 07 '20 at 19:50
  • 1
    Instead of lot of `strcmp` you can use https://www.gnu.org/software/gperf/ – Ôrel Dec 07 '20 at 19:52
  • actually what i mean by fail i try getch and readline but i couldn't implement so i removed and post clean code here @kaylum – Black Snow Dec 07 '20 at 20:03
  • 1
    You should post the code you tried that didn't work. Explain what problems/errors it has and then someone may be able to point out how to fix it. – kaylum Dec 07 '20 at 20:04
  • 1
    You at least need to find a way to clearly explain your goal. Linux doesn't have commands; you typically interact with a shell, like the one you're trying to write, and it parses and interprets commands. Input history isn't part of linux either. Some shells implement it, although they don't all implement it in the same way or with the same key strokes. – rici Dec 07 '20 at 20:37
  • 1
    I'd suggest [linenoise](https://github.com/antirez/linenoise) – Arkadiusz Drabczyk Dec 07 '20 at 20:38
  • actually it is just i want to create my own shell in C for linux terminal – Black Snow Dec 08 '20 at 05:44

0 Answers0