我的目标是让用户查看输入命令的历史记录(
historyArray
- 完成),并允许他通过输入 history 1
、history 2
(其中 1
和 2
)重新运行历史记录中的任何命令是从 historyArray
打印出来的命令列表的编号。
我已经设法从用户输入的第二个参数(history 1
)获取索引。我现在的问题是,如何执行从history N
获得的特定命令?
所以,例如:
hshell> test [Enter]
Command not found
hshell> history 1
Command not found
这是我的进步:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main (int argc, char *argv[])
{
int i=0; int j=0; int k=0;
int elementCounter = 0;
char inputString[100];
char *result=NULL;
char delims[] = " ";
char historyArray[30][20] = {0};
char tokenArray[20][20] ;
int tempIndex = 0;
char hCommand[2][20]={0};
do
{
j = 0;
printf("hshell>");
gets(inputString);
strcpy (historyArray[k], inputString);
k = (k+1) % 20;
if (elementCounter <= 20)
{
elementCounter++;
}
if (elementCounter == 21)
{
k = 20;
for (i=0; i<20; i++)
{
strcpy(historyArray[i], historyArray[i+1]);
}
strcpy (historyArray[19], inputString);
}
// Break the string into parts
result = strtok(inputString, delims);
while (result!=NULL)
{
strcpy(tokenArray[j], result);
j++;
result= strtok(NULL, delims);
}
if (strcmp(tokenArray[0], "exit") == 0)
{
return 0;
}
else if (strcmp(tokenArray[0], "history") == 0)
{
if (j>1)
{
tempIndex = atoi(tokenArray[1]);
strcpy(hCommand,historyArray[tempIndex-1]);
puts(hCommand);
// tempIndex = atoi(tokenArray[j]);
//puts(tempIndex);
}
else
{
//print history array
for (i=0; i<elementCounter-1;i++)
printf("%i. %s\n", i+1, historyArray[i]);
}
}
else
{
printf("Command not found\n");
}
}while (1);
}
hCommand
是我存储从 historyArray
获得的命令的位置。您可以使用unistd.h中的“系统”功能。
#include <unistd.h>
int system(const char *command);
windows 和 *nix 中都包含此功能。您无需担心分别致电
fork
或CreateProcess
,这将为您处理。有关详细信息,请参阅 MSDN 文档。
在你的代码中,你可以写:
system(hCommand);
命令完成后会返回(这是同步调用)。