934cbdbc63d7393317c0cc1643ff3d11f5d22844
[sdk/target/sdbd.git] / src / strutils.c
1 #include <stdio.h>
2 #include <stdlib.h>
3 #include <string.h>
4 #include "sysdeps.h"
5 #include "strutils.h"
6
7 #ifndef PATH_MAX
8 #define PATH_MAX 4096
9 #endif
10
11
12 size_t tokenize(const char *str, const char *delim, char *tokens[], size_t max_tokens ) {
13     int cnt = 0;
14
15     char tmp[PATH_MAX];
16
17     strncpy(tmp, str, PATH_MAX);
18     char *p = strtok(tmp, delim);
19     if (max_tokens < 1 || max_tokens > MAX_TOKENS) {
20         max_tokens = 1;
21     }
22
23     if (p != NULL) {
24         tokens[cnt++] = strdup(p);
25         while(cnt < max_tokens && p != NULL) {
26             p = strtok(NULL, delim);
27             if (p != NULL) {
28                 tokens[cnt++] = strdup(p);
29             }
30         }
31     }
32     return cnt;
33 }
34
35 void free_strings(char **array, int n)
36 {
37     int i;
38
39     for(i = 0; i < n; i++) {
40         if (array[i] != NULL) {
41             free(array[i]);
42         }
43     }
44 }
45
46
47 int read_line(const int fd, char* ptr, const unsigned int maxlen)
48 {
49     unsigned int n = 0;
50     char c[2];
51     int rc;
52
53     while(n != maxlen) {
54         if((rc = sdb_read(fd, c, 1)) != 1)
55             return -1; // eof or read err
56
57         if(*c == '\n') {
58             ptr[n] = 0;
59             return n;
60         }
61         ptr[n++] = *c;
62     }
63     return -1; // no space
64 }
65
66 /**
67  * The standard strncpy() function does not guarantee that the resulting string is null terminated.
68  * char ntbs[NTBS_SIZE];
69  * strncpy(ntbs, source, sizeof(ntbs)-1);
70  * ntbs[sizeof(ntbs)-1] = '\0'
71  */
72 char *s_strncpy(char *dest, const char *source, size_t n) {
73     char *start = dest;
74
75     while (n && (*dest++ = *source++)) {
76         n--;
77     }
78     if (n) {
79         while (--n) {
80             *dest++ = '\0';
81         }
82     }
83     return start;
84 }
85