Reputation: 21
I'm writing a program where it takes a command line then parse it ,in order to print an Array of strings of each argv in the input .
The code give me a segmentation fault (core dumped) !
#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;
}
Thank you for help .
Upvotes: 0
Views: 1034
Reputation: 968
I don't know what you try to achieve but:
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;
}
Upvotes: 1
Reputation: 40155
maybe like this
#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;
}
Upvotes: 0
Reputation: 2474
You can access each and every arguments using argv[][]
array . And argc
gives you number of arguments. This include program name itself.
For example:
c:\>test.exe arg1 arg2
here argc
will be 3 and
argv[0]="test.exe";
argv[1]="arg1";
argv[2]="arg2";
Or if you want to more interactive command line parsing check this one tclap
Upvotes: 1