【发布时间】:2015-10-07 04:13:57
【问题描述】:
我正在尝试实现一个外壳。我将创建一个 hist 数组来存储最后 10 个命令,我希望以后能够检索这些命令以便执行。因此,我正在尝试找到一种方法,一旦将所有命令行参数存储在该 hist 数组中,就可以将它们取回。
提供了一些代码,gettoks(),是一个获取和解析命令行输入的函数。函数 gettoks() 返回一个指向字符串的指针数组。每个字符串要么是包含字母、数字、. 和 / 的单词,要么是包含特殊字符之一的单个字符串:( ) | &;
我知道我可以将 toks 传递给 execvp,以便在执行命令后立即执行命令,但是一旦它存储在二维字符串数组中,我将如何检索它?
我也明白指针和数组可以让我的生活更轻松,但我对它们还是不太熟悉!所以,我想知道我是否可以得到一些关于代码的反馈并解决 "execvp(c[0] , c);" 行的编译错误。
“错误:从‘char’到‘const char*’的无效转换 错误:无法将参数‘2’的‘const char*’转换为‘char* const*’到‘int execvp(const char*, char* const*)’”
谢谢。
#include <iostream>
#include <unistd.h>
#include <sys/types.h>
#include <errno.h>
#include <signal.h>
#include <string.h>
#include <cstdlib>
#include <stdio.h>
using namespace std;
extern "C"
{
extern char **gettoks();
}
int main( int argc, char *argv[] )
{
// local variables
int ii;
char **toks;
int retval;
string tokenString;
string hist[11][2];
// initialize local variables
ii = 0;
toks = NULL;
retval = 0;
tokenString = "";
int m = 0; // command counter
for(int i = 0; i < 11; i++){ // initialize the hist array
for (int j = 0; j <2; j++){
hist[i][j]= "";
}
}
// main (infinite) loop
while( true )
{
// get arguments
toks = gettoks();
if( toks[0] != NULL ){ // if a command is entered
if ( m < 10){
m++; // increment the number of commands
for( ii=0; toks[ii] != NULL; ii++ ){ // add the command to the hist array
tokenString += toks[ii];
}
hist[m][0] = toks[0];
hist[m][1] = tokenString;
}
else if (m == 10){ // if the hist array is full
for( int k = 1; k < 10; k++ ){ // shift the commands in the hist array
for (int l = 0; l < 2; l++){
hist[k][l] = hist[k+1][l];
}
}
for( ii= 0; toks[ii] != NULL; ii++ ){ // add the new command to the hist array
tokenString += toks[ii];
}
hist[10][0] = toks[0];
hist[m][1] = tokenString;
}
}
for(int i = 1; i < 11; i++){// print the hist array
for (int j = 0; j <2; j++){
cout << hist[i][j] << "\t";
}
cout << endl;
}
tokenString = ""; // reset
const char * c = hist[1][1].c_str();
execvp(c[0] , c);
if( !strcmp( toks[0], "exit" ))
break;
}
// return to calling environment
return( retval );
}
【问题讨论】: