c - 解析 execve() 的命令行

标签 c strtok

我正在编写一个程序,它需要一个命令行然后解析它,以便在输入中打印每个 argv 的字符串数组。

代码给我一个段错误(核心转储)!

#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;

  } 

谢谢你的帮助。

最佳答案

您可以使用 argv[][] array 访问每个参数。 argc 为您提供参数数量。这包括程序名称本身。 例如:

c:\>test.exe arg1 arg2

这里 argc 将是 3 并且

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

或者,如果你想要更多交互式命令行解析,请检查这个 tclap

关于c - 解析 execve() 的命令行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16496857/

相关文章:

c - curl/curl.h、libcurl、libcurl4-openssl-dev、libcurl4-nss-dev 库之间的区别?

c - 返回一个大变量与使用参数中提供的指针设置它

c - __builtin_types_compatible_p(t1, t2) 和指向限定类型​​的指针

c - 如何在文本文件中使用strtok

c - strtok 没有正确分割字符串

c - 在 C 中使用 Strtok 获取字符串

c - 数字计数器的循环不起作用

c - 描述和重写试卷中的示例代码

c - 下次调用函数后,上次调用的字符串 "remembered"

c++ - 以 24 小时格式表示的两次时间之间耗时 hh :mm:ss