I am quite familiar with Python coding but now I have to do stringparsing in C.
My input:
input = "command1 args1 args2 arg3;command2 args1 args2 args3;cmd3 arg1 arg2 arg3"
My Python solution:
input = "command1 args1 args2 arg3;command2 args1 args2 args3;command3 arg1 arg2 arg3"
compl = input.split(";")
tmplist =[]
tmpdict = {}
for line in compl:
spl = line.split()
tmplist.append(spl)
for l in tmplist:
first, rest = l[0], l[1:]
tmpdict[first] = ' '.join(rest)
print tmpdict
#The Output:
#{'command1': 'args1 args2 arg3', 'command2': 'args1 args2 args3', 'cmd3': 'arg1 arg2 arg3'}
Expected output: Dict with the command as key and the args joined as a string in values
My C solution so far:
I want to save my commands and args in a struct like this:
struct cmdr{
char* command;
char* args[19];
};
I make a struct char* array to save the cmd + args seperated by ";":
struct ari { char* value[200];};
The function:
struct ari inputParser(char* string){
char delimiter[] = ";";
char *ptrsemi;
int i = 0;
struct ari sepcmds;
ptrsemi = strtok(string, delimiter);
while(ptrsemi != NULL) {
sepcmds.value[i] = ptrsemi;
ptrsemi = strtok(NULL, delimiter);
i++;
}
return sepcmds;
- Seperate commands and arrays by space and save them in my struct:
First I added a help struct:
struct arraycmd {
struct cmdr lol[10];
};
struct arraycmd parseargs (struct ari z){
struct arraycmd result;
char * pch;
int i;
int j = 0;
for (i=0; i < 200;i++){
j = 0;
if (z.value[i] == NULL){
break;
}
pch = strtok(z.value[i]," ");
while(pch != NULL) {
if (j == 0){
result.lol[i].command = pch;
pch = strtok(NULL, " ");
j++;
} else {
result.lol[i].args[j]= pch;
pch = strtok(NULL, " ");
j++;
}
}
pch = strtok(NULL, " ");
}
return result;
My output function looks like this:
void output(struct arraycmd b){
int i;
int j;
for(i=0; i<200;i++){
if (b.lol[i].command != NULL){
printf("Command %d: %s",i,b.lol[i].command);
}
for (j = 0; j < 200;j++){
if (b.lol[i].args[j] != NULL){
printf(" Arg %d = %s",j,b.lol[i].args[j]);
}
}
printf(" \n");
}
}
But it produces only garbage (Same input as in my python solution) :
(command1 args1 args2 arg3;command2 args1 args2 args3;command3 arg1 arg2 arg3 )
Command 0: command1 Arg 0 = command2 Arg 1 = args1 Arg 2 = args2 Arg 3 = arg3 Arg 19 = command2 Arg 21 = args1 Arg 22 = args2 Arg 23 = args3 Arg 39 = command3 Arg 41 = arg1 Arg 42 = arg2 Arg 43 = arg3 Segmentation fault
So I hope someone can help me to fix this.