2013-05-11 83 views
0

我正在編寫一個程序,它需要一個命令行然後解析它,以便在輸入中打印每個argv的字符串數組。解析execve的命令行()

該代碼給我一個分段錯誤(核心轉儲)!

#include <stdio.h> 
#include <string.h> 
#include <unistd.h> 
#include <stdlib.h> 

char **parse(int position ,char *argv[] ) ; 
int main(int argc ,char *argv[]) 
{ 

    int i=1; 
    int f=argc; 
    argc--; 
    while(i<f) 
    { 
    char commands[10]; 
    char **argument=parse(argc,argv); 
    //parse(i ,argv ,commands ,argument) ; 
    printf("the argument[ %i ] is :%s \n",i,argument[i]); 

    argc-- ; 
    i++; 
    } 
    } 

char **parse(int position ,char *argv[]) 
{ 
    // char *commands; 
    char** arguments; 
    char *result ; 
    char buffer [30] ; 
    int count =0; 

    arguments = calloc(1, sizeof (char *)); 

    strcpy(buffer,argv[position-1]); //copy the current argv to the buffer 

    result =strtok(buffer," "); 
    // strcpy(commands,result); 
    //result =strtok(buffer," "); 
    while(result !=NULL) 
     { 

     arguments[count] =result ; 
     ++count; 
     arguments = realloc(arguments, sizeof (char *) * (count + 1));    
     result=strtok(NULL," "); 
     } 
    arguments[count] = NULL; //in order to call the execvp 



    return arguments; 

    } 

謝謝你的幫忙。

回答

1

我不知道你試圖實現什麼,但:

int main(int argc ,char **argv) 
{ 
    int i; 

    for(i=1; i<argc; ++i) 
    { 
     printf("the argument[ %i ] is :%s \n",i,argv[i]); 
    } 
    return 0; 
} 
+0

Y你永遠不允許'void' main()。 – 2013-05-12 05:48:20

+0

單詞。已更改.... – 2013-05-12 08:00:40

1

您可以訪問使用argv[][]陣列的每一個參數。而argc給你的參數數量。這包括程序名稱本身。 例如:

c:\>test.exe arg1 arg2 

這裏argc將是3和

argv[0]="test.exe"; 
argv[1]="arg1"; 
argv[2]="arg2"; 

或者,如果你想要更多的互動命令行解析檢查這一個tclap

+0

而'argv [3] = NULL'。 – user9876 2013-05-11 12:28:27

+0

訪問argv [3]將導致段錯誤。 – Sanoob 2013-05-11 12:29:48

+1

請參閱C規範(例如http://www.open-std.org/jtc1/sc22/wg14/www/docs/n1539.pdf的草稿 - 您必須支付最終版本)「5.1.2.2。 1程序啓動「中說」argv [argc]應該是一個空指針「。所以'argv [3] = NULL'由標準保證。 – user9876 2013-05-11 12:57:33

0

也許這樣

#include <stdio.h> 
#include <string.h> 
#include <unistd.h> 
#include <stdlib.h> 

char **parse(int position , char *argv[], char *outputbuff); 
int main(int argc ,char *argv[]){ 
    int i; 
    for(i=1;i<argc;++i) { 
     char commands[30]; 
     char **argument; 
     argument=parse(i ,argv ,commands); 
     { 
      int j; 
      for(j=0;argument[j]!=NULL;++j) 
       printf("the argument[ %i ] is :%s \n", j, argument[j]); 
     } 
     free(argument); 
    } 
    return 0; 
} 

char **parse(int position ,char *argv[], char *commands){ 
    char **arguments; 
    char *result ; 
    int count =0; 

    arguments = calloc(1, sizeof (char *)); 
    strcpy(commands, argv[position]); 
    result =strtok(commands," "); 
    while(result !=NULL){ 
     arguments[count] =result ; 
     ++count; 
     arguments = realloc(arguments, sizeof(char*)*(count + 1));    
     result=strtok(NULL," "); 
    } 
    arguments[count] = NULL; 

    return arguments; 
}