I'm trying to read in command lines such as "ls -la /tmp" and need to split them into a char pointer array. I read in an input using getline() and pass the input and pointer array to the function and "i" return the number of commands/args so in this case 3. I want to be able to ignore/remove any whitespace and not seg fault on empty lines, like a line full of tabs, so each array index would point to "ls", "-la", "/tmp" respectively. Any help greatly appreciated.
int string_split(char * input, char * commands[]) {
int i = 0;
const char * delim = " \t\r\n\a";
//Remove trailing newline character
input[strcspn(input, "\n")] = '\0';
//Break user input into each command using fixed delimiter
while((commands[i] = strsep(&input, delim)) != NULL) {
//Each break counted then returned to reference number of command/arguments
i++;
}
return i;
}
Prefer to use strsep over strtok/strtok_r, I've tried both and run into seg faults constantly. Starting code prior to calling function:
char * input = NULL;
size_t input_size = 0;
char * command_line[10];
int res = getline(&input, &input_size, stdin);
if(res == -1) {
exit(0);
}
//String contains only newline character
else if(res == 1) {
continue;
}
else {
//Break string into seperate command and arguments then stores number of commands/arguments
int input_length = string_split(input, command_line);
//Code continues on to handling...
You can easily create such function yourself.
To do not count empty strings add
if(strchr(delim, *str)) continue;after `*str++ = 0;usage:
https://godbolt.org/z/soPafqfrd
Result: