Throttler.pm dependencies
[hband-tools.git] / ssh-groupcommand / libstrtokdup.c
blobafb5ddb14eb381decaf7d225666ba1c161feb397
2 #include <string.h>
3 #include <stdio.h>
4 #include <ctype.h>
6 #include "libmallocab.h"
8 #define DEBUG_LIBSTRTOKDUP 0
11 Return a pointer to a copy of n-th word of a string.
12 Return NULL if there are not enough words.
13 Count starts at 1.
14 Words are separated by whitespace
15 Caller is responsible to free() the returning pointer.
18 char* strtokdup(const char* s, unsigned int nth)
20 char* r;
21 unsigned int i, L;
23 #if DEBUG_LIBSTRTOKDUP
24 fprintf(stderr, "strtokdup('%s', %d)\n", s, nth);
25 #endif
26 if(s == NULL)
27 return NULL;
29 i = 0;
30 /* Jump to nth token */
31 while(nth > 0)
33 /* Strip leading whitespace */
34 while(isspace(s[i]) && s[i] != '\0') i++;
35 if(s[i] == '\0')
36 return NULL;
37 if(nth > 1)
39 /* Skip to next whitespace */
40 while(!isspace(s[i]) && s[i] != '\0') i++;
41 if(s[i] == '\0')
42 return NULL;
44 nth--;
47 L = strcspn(s+i, " \f\n\r\t\v");
48 r = mallocab(L+1);
49 strncpy(r, s+i, L);
50 r[L] = '\0';
51 #if DEBUG_LIBSTRTOKDUP
52 fprintf(stderr, " -> '%s'\n", r);
53 #endif
54 return r;