0

我正在尝试在 shell 中创建一个简单的历史函数,但由于某种原因,当我写入历史文本文件时,它会复制输入。例如,用户输入 hello,然后是 hi,然后是 bonjour,然后是 history。这个历史文件看起来像: hello hello hi hello hi bonjour hello hi bonjour history 。我的历史文件应该只说你好你好 bonjour 历史。

这是我的代码:

#include "parser.h"
#include "shell.h"
#include <stdio.h>
#include <string.h>
int main(void) {
  char input[MAXINPUTLINE];
  FILE *ptr_file;
  int count=1;
  char *history="history";
  char *last="!!";
  ptr_file =fopen(".simpleshell_history", "w");
  //ptr_file =fopen(".variables", "w");
  signal_c_init();

  printf("Welcome to the sample shell!  You may enter commands here, one\n");
  printf("per line.  When you're finished, press Ctrl+D on a line by\n");
  printf("itself.  I understand basic commands and arguments separated by\n");
  printf("spaces, redirection with < and >, up to two commands joined\n");
  printf("by a pipe, tilde expansion, and background commands with &.\n\n");

  printf("\nlpsh$ ");

  while (fgets(input, sizeof(input), stdin)) {
    stripcrlf(input);
    parse(input);
    //printf(input);
    if(strcmp(input, last)==0) {
        fclose(ptr_file);
        char buf[1000];
        ptr_file =fopen(".simpleshell_history","r");
        while(fgets(buf,1000, ptr_file)!=NULL) {
        }
        memmove(buf, buf+2, strlen(buf));
        printf(buf);

    }
    fprintf(ptr_file,"%i ", count);
    fprintf(ptr_file,"%s\n", input);
    count++;
    if(strcmp(input, history)==0) {
        //printf("it works");
        fclose(ptr_file);
        char buf[1000];
        ptr_file =fopen(".simpleshell_history","r");
    while (fgets(buf,1000, ptr_file)!=NULL) {
            printf("%s",buf);
    }
    fclose(ptr_file);
    ptr_file =fopen(".simpleshell_history","a");
}

    printf("\nlpsh$ ");
  }



  fclose(ptr_file);
  return 0;
}
4

0 回答 0