Skip to content

Instantly share code, notes, and snippets.

@dirkjanfaber
Created June 1, 2017 09:31
Show Gist options
  • Save dirkjanfaber/0ee9432cb7eca59d4b0813ad605f8539 to your computer and use it in GitHub Desktop.
Save dirkjanfaber/0ee9432cb7eca59d4b0813ad605f8539 to your computer and use it in GitHub Desktop.
split a commandline into command and paramters
#include <stdio.h>
#include <stdlib.h>
#include <stdint.h>
#include <ctype.h>
#include <string.h>
typedef struct
{
char *command;
char *parameter1;
char *parameter2;
} tCommandLine;
void ToLower(char *str) {
int i = 0;
for (i=0; str[i]; i++) {
str[i] = tolower(str[i]);
}
}
// Function to get the nth parameter word of a string, splitting on spaces
void get_param(char * str, char * value, int n) {
int start = 0, length = 0, m = 0;
printf("Searching for %dth parameter of [%s]\n", n, str);
for (int i=0; i<(strlen(str)); i++) {
if ( str[i] == ' ' ) {
m++;
if ( m == ( n - 1 ) ) {
start = i+1;
} else if ( m == n ) {
length = i - start;
break;
}
}
}
// Voor de laatste parameter
if ( length == 0 ) {
length = strlen(str) - start;
}
// Veiligheid, we mogen niet langer kopieren dan we ruimte hebben
if ( length > sizeof(value) ) {
length = sizeof(value);
}
printf("start = %d, lenght = %d\n", start, length);
if ( length > 0 ) {
memcpy(value, &str[start], length);
}
return;
}
int main ( int argc, const char * argv[]) {
char *input = "one two three four five";
tCommandLine cmd;
cmd.command = malloc(8);
cmd.parameter1 = malloc(8);
cmd.parameter2 = malloc(8);
get_param(input, cmd.command, 1 );
get_param(input, cmd.parameter1, 2 );
get_param(input, cmd.parameter2, 3 );
printf("Command = [%s]\n", cmd.command);
printf("Param 1 = [%s]\n", cmd.parameter1);
printf("Param 2 = [%s]\n", cmd.parameter2);
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment