I'm trying to parse an input string into a command string and an array of arguments strings.
I'm having some issue using strtok and strcpy, I think that my command string is not being null terminated properly which is leading to the seg fault.
#include <stdio.h>
#include <string.h>
#define delims " \t\r\n"
int main() {
char input[] = "ls -a -f";
char *buffer;
char command[256];
char arguments[256][256];
int i = 0, j;
buffer = strtok(input, delims);
strcpy(command, buffer);
printf("Command: %s\n\r", command);
while (buffer != NULL)
{
buffer = strtok(NULL, delims);
strcpy(arguments[++i], buffer);
}
buffer = strtok(NULL, delims);
for (j = 0; j < i; ++i)
{
printf("Argument[%d]: %s", j, arguments[j]);
}
return 0;
}
Current Output:
Command: ls
Segmentation fault: 11
Expected Output:
Command: ls
Argument[0]: -a
Argument[1]: -f
I don't pretend to be very good with C, so any pointers in the right direction would be extremely helpful.