c中简单shell程序中的历史实现

时间:2011-02-19 11:18:47

标签: c

我是新人并且自己学习c。我设法用c写了一个简单的shell代码,但我现在的问题是输入命令,这样当输入命令“history”时,最近输入的命令会显示在屏幕上。一个示例代码或任何材料,以帮助我有我的shell有历史将不胜感激。

1 个答案:

答案 0 :(得分:4)

有很多方法可以实现这一目标。您可以使用GNU readline library,这对于那种事情非常好。这将提供的不仅仅是一个简单的history命令。

但实施简单的历史记录会更容易。如果你对历史中的命令有一个固定的限制,那么一个简单的数组就足够了,可能是这样的:

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 );
    }
}