将数组的值传递到循环的开头

问题描述 投票:0回答:2

我的目标是让用户查看输入命令的历史记录(

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
    获得的命令的位置。
  • 我使用的是 Windows 机器。
c arrays
2个回答
1
投票

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

编辑#1那么我相信你需要这个API。请注意,我不熟悉其中哪些功能与我首先提供的功能相同。花一点时间你就能弄清楚,对吧? :)


0
投票

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

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

windows 和 *nix 中都包含此功能。您无需担心分别致电

fork
CreateProcess
,这将为您处理。有关详细信息,请参阅 MSDN 文档

在你的代码中,你可以写:

system(hCommand);

命令完成后会返回(这是同步调用)。

© www.soinside.com 2019 - 2024. All rights reserved.