【问题标题】:How to handle history limit of 100 for my own shell's history function如何为我自己的 shell 的历史功能处理 100 的历史限制
【发布时间】:2021-02-07 17:46:23
【问题描述】:

这是我的问题:我正在构建自己的 shell,并实现了一个历史函数,唯一的问题是历史数组只能取 100 个值,最后 100 个值意味着当它超过 100 时,第一个值得到删除后,每个值都向后移动一个索引,最后一个值获得第 100 位。我唯一的问题是,无论我尝试什么,我的程序的其余部分都会开始出现问题(因此注释行)有什么方法可以使它工作?

这是我的代码:

void hist_add(const char *cmd)
{
    if(history_counter<100){
    strcpy(history_array[history_counter].command_stored, cmd);
    history_array[history_counter].command_number = 1111;
    history_counter++;
    }
//    else {
//        for(int j=0;j<100;j++){
//            strcpy(history_array[j].command_stored, history_array[j+1].command_stored);
//        }
//        strcpy(history_array[history_counter].command_stored, cmd);
//        history_array[history_counter].command_number = 1111;
//        history_counter++;
//    }
}

P.S:到目前为止,每个命令的 command_number 都是 1111,因为我接下来要实现它。

【问题讨论】:

  • 所以我应该让它循环直到它达到 99?
  • 正在写答案,请稍候。
  • 我的建议是不要移动元素。而是使用模运算让计数器(数组索引)再次从99 环绕到0。当然,在历史记录中倒退时需要一个特殊情况(从099),但通常这比每次向历史记录中添加新命令时都移动每个元素更容易(而且工作量要少得多)。

标签: arrays c shell for-loop history


【解决方案1】:
  • 将 100 元素数组的元素移动 1 次,而不是 100 次移动,将有 99 次移动。最后 1 步被省略了,因为它把一个元素放到了数组之外。
  • 班次正在删除一个元素。现在使用 history_counter 作为索引是错误的,因为计数应该根据 drop 递减。

固定代码为:

    else {
        for(int j=0;j+1<100;j++){ /* use j+1<100, not j<100, to avoid out-of-range access */
            strcpy(history_array[j].command_stored, history_array[j+1].command_stored);
        }
        history_counter--; /* decrement history_counter according to the drop */
        strcpy(history_array[history_counter].command_stored, cmd);
        history_array[history_counter].command_number = 1111;
        history_counter++;
    }

或者省略匹配的减量和增量,可以这样写:

    else {
        for(int j=0;j+1<100;j++){ /* use j+1<100, not j<100, to avoid out-of-range access */
            strcpy(history_array[j].command_stored, history_array[j+1].command_stored);
        }
        /* use history_counter-1 instead of history_counter */
        strcpy(history_array[history_counter-1].command_stored, cmd);
        history_array[history_counter-1].command_number = 1111;
    }

j+1&lt;100 可以写成j&lt;100-1。使用常量值(可能是宏)而不是幻数 100 将进一步改进您的代码。

【讨论】:

  • 如果我们仍然需要计数来显示实际命令的计数,代码会是什么样子。像只有 100 个命令,但索引 319 到 419 例如
  • 去掉history_counter——但保留history_counter++就行了?
  • 我会在变量history_counter旁边添加另一个变量来跟踪实际命令的计数,该变量用于跟踪数组中的命令数
  • 好的!那么将它一直添加到结构中?
  • 不使用 history_counter--; 并将新命令的索引更改为 100-1 也可以。
猜你喜欢
  • 2013-11-21
  • 2013-12-25
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2010-11-06
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多