c - 如何实现历史记录功能?

标签 c shell command-line

我是 C 编程新手,目前正在学习这门类(class)。我在尝试练习以下历史记录功能时遇到问题。

我能够显示 shell 命令。但是,当我输入历史记录时,过去的 shell 命令不会保存到历史缓冲区中。

谁能帮我找出哪里出错了?

这是我的代码:

#include<stdio.h>
#include<unistd.h>
#include<string.h>
#define BUFSIZE     20  
#define MAX_WORD_IN_LINE 20 

int tokenize(char *str, char **args)
{
    int i, argc = 0;
    char *token;

    token = strtok(str," \t\n");
    for(i=0; token!=NULL;i++)
        {
            args[i] = token;
            printf("args[%d] = %s\n", i, args[i]);
            token = strtok(NULL, " \t\n");
            argc++;
        }
    return argc;
}

void display_strings(char **p)
{
    if (p == NULL) return;
    while(*p != NULL){
        printf("%s\n",*p);
        p++;
    }
}

int history(char *hist[], int current){
    int i = current;
    int hist_num = 1;

    do {
        if (hist[i]) {
            printf("%4d  %s\n", hist_num, hist[i]);
            hist_num++;
        }

        i = (i + 1) % BUFSIZE;

    } while (i != current);

    return 0;
}

int main(void){
    char *args[MAX_WORD_IN_LINE];
    char buffer[BUFSIZE];
    char *hist[BUFSIZE];
    int i,current=0;

    pid_t   pid;
    int argc;

    for(i=0;i<BUFSIZE;i++)
        hist[i]= NULL;

    while(1) {
        memset(args,0,MAX_WORD_IN_LINE);
        printf("osh> ");
        fgets(buffer, BUFSIZE, stdin);
        argc = tokenize(buffer, args);
        //display_strings(args);

        // skip on empty command
        if (argc == 0) continue;

        if (strcmp(args[0],"quit") == 0) break;
        else if (strcmp(args[0], "hello") == 0) printf("Hello there. How are you?\n");
        else if (strcmp(args[0],"history")==0) history(hist,current);
        else {
            pid = fork();
            if (pid == 0) {

                hist[current]=strdup(args[0]);
                current++;

                execvp(args[0], args);
                return 0;
            }

最佳答案

当您将 args[0] 指向的字符串保存到 hist 中时,您需要复制该字符串。目前,您只是将指针分配给当前的 args[0],它将被下一个命令覆盖。当您打印历史记录时,您只会重复获得最后一个命令。所以使用:

hist[current] = strdup(args[0]);

关于c - 如何实现历史记录功能?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32662541/

相关文章:

C - 无法使用remove()删除文件夹中的文件

wpf - 如何将 Shell 中的按钮绑定(bind)到已加载模块的 View 模型中定义的命令?

用于自动生成 cntlm 代理密码的 Bash 脚本

php - $_SERVER 未使用命令行 -r 选项设置?

python - 在 Mac Os 中编译和链接 Python 模块

c - 如何用C实现无限极限梯形积分?

windows - 查找在日期之间创建/访问/修改的文件,批处理脚本

visual-studio - 如何从命令行编译 MSVC 项目中的单个源文件?

c++ - Libunwind PC 值不适用于 addr2line

linux - 在 while 循环中使用 SSH 丢失属性值