Created
June 1, 2017 09:31
-
-
Save dirkjanfaber/0ee9432cb7eca59d4b0813ad605f8539 to your computer and use it in GitHub Desktop.
split a commandline into command and paramters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#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