How to use the C programming language by creating a shell that can implement a history capture arrow?

advertisements

I have saved the history of the previous commands in a two-dimensional array. But I don't know how to check the up arrow.

How to use the C programming language implementing this feature (in Linux)?


Thanks to n.m. for good advice.

The following is the example of usage libreadline:

// rltest.c
#include <stdio.h>
#include <stdlib.h>
#include <readline.h>
#include <history.h>

int main(void)
{
    char* input, shell_prompt[100];
    // Configure readline to auto-complete paths when the tab key is hit.
    rl_bind_key('\t', rl_complete);
    // while work is not 0 program executes the loop
    int work = 1;
    printf("Commands to use: name, ver, exit \n");
    // loop for working with commands
    while(work) {
        // Build prompt string.
        snprintf(shell_prompt, sizeof(shell_prompt), "your command $ ");
        // Display prompt and read input
        input = readline(shell_prompt);
        // Check for EOF.
        if (!input)
            break;
        // Add input to history.
        add_history(input);
        // Command analysis and execution
        if( 0 == strcmp(input, "exit") )
        {
            printf("Bye!\n");
            work = 0;
        }
        if( 0 == strcmp(input, "name") )
        {
            printf("I'm readline example\n");
        }
        if( 0 == strcmp(input, "ver") )
        {
            printf("My version is 0.1\n");
        }
        // ...
        // Free input for future use
        free(input);
    }
    return 0;
}

to compile this example:

1) install readline library

 apt-get install libreadline-dev

2) compile program as

 gcc rltest.c -I/usr/include/readline -lreadline