gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-30 15:51:25 25 4
gpt4 key购买 nike

我的目标是让用户查看输入命令的历史记录(historyArray - 完成),并允许他通过输入history 1来重新运行历史记录中的任何命令>, history 2 其中 12 是从 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 计算机。

最佳答案

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

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

关于c - 将数组的值传递到循环的开头,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15092561/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com