我正在尝试在shell中创建一个简单的历史记录函数,但出于某种原因,当我写入历史文本文件时,它会复制输入。例如,用户输入你好,然后输入你好,然后是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;
}