danielhilst

strtoknize.c

Jan 25th, 2013
79
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C 1.20 KB | None | 0 0
  1. #include <alloca.h>
  2. #include <assert.h>
  3. #include <stdio.h>
  4. #include <stdlib.h>
  5. #include <string.h>
  6.  
  7. char **strtoknize(const char *str, size_t slen, const char *dlmt, int dlen, int  *n_toks)
  8. {
  9.         char *toks = alloca(slen);
  10.         char *save_ptr = NULL;
  11.         char *ptr = NULL;
  12.         int i;
  13.         char **buffer = NULL;
  14.  
  15.         strncpy(toks, str, slen);
  16.  
  17.         if (!strcmp(&toks[slen - dlen], dlmt)) {
  18.                 toks[slen - dlen] = '\0';
  19.         }
  20.  
  21.         i = 0;
  22.         ptr = strtok_r(toks, dlmt, &save_ptr);
  23.         while (ptr) {
  24.                 i++;
  25.                 buffer = realloc(buffer, sizeof (char **) * i);
  26.                 assert(buffer);
  27.                 buffer[i - 1] = strdup(ptr);
  28.                 assert(buffer[i - 1]);
  29.                 ptr = strtok_r(NULL, dlmt, &save_ptr);
  30.         }
  31.  
  32.         *n_toks = i;
  33.         return buffer;
  34. }
  35.  
  36. int main(void)
  37. {
  38.         char **buffer;
  39.         int i;
  40.         int n_toks;
  41.        
  42. #define STR "foo||bar||tar||zar||"
  43.         buffer = strtoknize(STR, strlen(STR),
  44.                             "||", 2, &n_toks);
  45.  
  46.         for (i = 0; i < n_toks; i++) {
  47.                 puts(buffer[i]);
  48.         }
  49.  
  50.         return 0;
  51. }
Advertisement
Add Comment
Please, Sign In to add comment