Merge branch 'tizen_2.4_merge' into tizen
[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+1];
16     char *ptr;
17
18     strncpy(tmp, str, PATH_MAX);
19     tmp[PATH_MAX] = '\0';
20
21     char *p = strtok_r(tmp, delim, &ptr);
22     if (max_tokens < 1 || max_tokens > MAX_TOKENS) {
23         max_tokens = 1;
24     }
25
26     if (p != NULL) {
27         tokens[cnt++] = strdup(p);
28         while(cnt < max_tokens && p != NULL) {
29             p = strtok_r(NULL, delim, &ptr);
30             if (p != NULL) {
31                 tokens[cnt++] = strdup(p);
32             }
33         }
34     }
35     return cnt;
36 }
37
38 void free_strings(char **array, int n)
39 {
40     int i;
41
42     for(i = 0; i < n; i++) {
43         if (array[i] != NULL) {
44             free(array[i]);
45         }
46     }
47 }
48
49
50 int read_line(const int fd, char* ptr, const unsigned int maxlen)
51 {
52     unsigned int n = 0;
53     char c[2];
54     int rc;
55
56     while(n != maxlen) {
57         if((rc = sdb_read(fd, c, 1)) != 1)
58             return -1; // eof or read err
59
60         if(*c == '\n') {
61             ptr[n] = 0;
62             return n;
63         }
64         ptr[n++] = *c;
65     }
66     return -1; // no space
67 }
68
69 /**
70  * The standard strncpy() function does not guarantee that the resulting string is null terminated.
71  * char ntbs[NTBS_SIZE];
72  * strncpy(ntbs, source, sizeof(ntbs)-1);
73  * ntbs[sizeof(ntbs)-1] = '\0'
74  */
75
76 char *s_strncpy(char *dest, const char *source, size_t n) {
77
78     char *start = dest;
79
80     while(n && (*dest++ = *source++)) {
81         n--;
82     }
83
84     if (n) {
85         while (--n) {
86             *dest++ = '\0';
87         }
88     }
89     return start;
90 }