0

我的目标是让用户查看输入命令的历史记录(historyArray-done),并允许他重新运行历史记录中的任何命令,方法是输入history 1, history 2where12is the number of commands as print out from 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.
  • 我正在使用 Windows 机器。
4

2 回答 2

1

在获得您要执行的命令的名称后,我建议您通过系统调用exec。考虑到exec将当前进程映像替换为您要执行的进程映像。否则你可能会对fork感兴趣。

EDIT#1然后我相信你需要这个 API。请注意,我不熟悉哪些功能与我首先提供的功能等效。稍微花点时间你就能弄清楚,对吧?:)

于 2013-02-26T15:15:48.007 回答
0

您可以使用 stdlib.h 中的“系统”功能。

#include <stdlib.h>
int system(const char *command);

这个函数包含在 windows 和 *nix 中。您无需担心打电话forkCreateProcess单独打电话,这将为您处理。有关详细信息,请参阅MSDN 文档

在您的代码中,您将编写:

system(hCommand);

当命令完成时它将返回(这是一个同步调用)。

于 2013-02-26T15:34:24.677 回答