开发者

History implementation in a simple shell program in c

i'm new and learning c on my own. i managed to write a simple shell code in c but my problem now is to have commands entered stored so that when entering a command "history" the recently entered commands are displayed on screen. a sample code or any materials to read to help 开发者_如何学Pythonme have my shell have history will be appreciated.


There are many ways to achieve this. You could use the GNU readline library, which is really nice for that sort of thing. This would provide much more than a simple history command.

But just implementing a simple history would be easier. If you have a fixed limit for commands in the history a simple array would be sufficient, maybe like this:

static const char *history[HISTORY_MAX_SIZE];
static const unsigned history_count = 0;

void add_command_to_history( const char *command )
{
   if (history_count < HISTORY_MAX_SIZE) {
        history[history_count++] = strdup( command );
   } else {
        free( history[0] );
        for (unsigned index = 1; index < HISTORY_MAX_SIZE; index++) {
            history[index - 1] = history[index];
        }
        history[HISTORY_MAX_SIZE - 1] = strdup( command );
    }
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜