我試圖實現一個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);
}