この問題を修正するのに 2 日間苦労していますが、何もうまくいかないようです! 私は C でシェルを作成しており、履歴コマンド (ユーザーが指定したすべてのコマンドの履歴を保持します) を実装しようとしています。これは私のコードの簡略版です (不要なコードと関数を削除しました)。
#include <stdio.h>
#include <string.h>
int main()
{
int doLoop = 1;
int i=0;
int c=0;
char givenCommand[100];
char *history[20];
char *newlinePos; /* pointer to the '\n' character in the input C string */
/* Print the header */
printf("Operating Systems Shell (Fall 2013)\n");
printf("Iacovos Hadjicosti\n");
printf("\n");
while(doLoop==1) /* Check if it should do the loop again */
{
printf("CSC327>"); /* Print a new prompt line */
fgets(givenCommand, sizeof(givenCommand), stdin); /* get input */
newlinePos = strchr(givenCommand,'\n'); /* point newlinePos to the '\n' character */
if(newlinePos!=NULL)
{
*newlinePos = '\0'; /* replace it with the null character */
}
if(strcmp(givenCommand,"exit")==0)
{
doLoop = 0; /* Do not do the loop again */
}
else if(strcmp(givenCommand,"history")==0)
{
for(i=0; i<c; i++)
{
printf("%d. %s\n", i+1, history[i]);
}
}
else
{
if(strcmp(givenCommand,"")!=0) /* if input was not empty.. */
{
printf("Command not found!\n"); /* show wrong command message */
}
}
history[c] = givenCommand;
c++;
}
return 0;
}
これは入力を取得し、それを givenCommand に入れ、それがどのコマンドであったかを確認してから、履歴配列に入れます。ユーザーが「history」コマンドを実行すると、履歴配列内のすべてのコマンドが出力されます。代わりに、最後に与えられたコマンドだけを c 回出力します (c は与えられたコマンドの総数です)。
たとえば、ユーザーが「Test1」と入力し、次に「Test2」と入力し、3 回目に「history」と入力すると、次のように出力されます。
1.テスト2
2.テスト2
これを解決する方法について意見はありますか?(私は TCC を使用してコンパイルしています)