2015-10-07 224 views
3

我试图实现一个shell。我将创建一个hist数组来存储最后的10个命令,我希望能够稍后检索以执行。所以,我试图找到一种方法来获取所有命令行参数,一旦我将它们存储在该hist数组中。不能将'const char *'转换为'char * const *'

提供了一些代码,gettoks()是获取和分析命令行输入的函数。函数gettoks()返回一个指向字符串的指针数组。每个字符串都是包含字母,数字,。和/的单词,或者是包含其中一个特殊字符的单个字符串:()<> | &;

我知道我可以传递给execvp,执行它后立即执行命令,但是一旦它存储在一个2d字符串数组中,我将如何检索它?

我也明白,指针和数组可以使我的生活更轻松,但我仍然不那么熟悉它们!所以,我想知道是否可以在代码上获得一些反馈,并在“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); 
} 

回答

2

execvp意像使用:

char* cmd[] = { "sleep", "1", NULL }; 
execvp(cmd[0], cmd); 

但在你的代码,你逝去的c这是一个普通的C字符串(const char *)。您可以直接使用由gettoks()函数返回的数组与execvp

相关问题