/src/clib/deps/path-join/path-join.c
Line | Count | Source |
1 | | |
2 | | // |
3 | | // path-join.c |
4 | | // |
5 | | // Copyright (c) 2013 Stephen Mathieson |
6 | | // MIT licensed |
7 | | // |
8 | | |
9 | | #include <string.h> |
10 | | #include <stdlib.h> |
11 | | #include "strdup/strdup.h" |
12 | | #include "str-ends-with/str-ends-with.h" |
13 | | #include "str-starts-with/str-starts-with.h" |
14 | | #include "path-join.h" |
15 | | |
16 | | #ifdef _WIN32 |
17 | | #define PATH_JOIN_SEPERATOR "\\" |
18 | | #else |
19 | 0 | #define PATH_JOIN_SEPERATOR "/" |
20 | | #endif |
21 | | |
22 | | /* |
23 | | * Join `dir` with `file` |
24 | | */ |
25 | | |
26 | | char * |
27 | 0 | path_join(const char *dir, const char *file) { |
28 | 0 | int size = strlen(dir) + strlen(file) + 2; |
29 | 0 | char *buf = malloc(size * sizeof(char)); |
30 | 0 | if (NULL == buf) return NULL; |
31 | | |
32 | 0 | strcpy(buf, dir); |
33 | | |
34 | | // add the sep if necessary |
35 | 0 | if (!str_ends_with(dir, PATH_JOIN_SEPERATOR)) { |
36 | 0 | strcat(buf, PATH_JOIN_SEPERATOR); |
37 | 0 | } |
38 | | |
39 | | // remove the sep if necessary |
40 | 0 | if (str_starts_with(file, PATH_JOIN_SEPERATOR)) { |
41 | 0 | char *filecopy = strdup(file); |
42 | 0 | if (NULL == filecopy) { |
43 | 0 | free(buf); |
44 | 0 | return NULL; |
45 | 0 | } |
46 | 0 | strcat(buf, ++filecopy); |
47 | 0 | free(--filecopy); |
48 | 0 | } else { |
49 | 0 | strcat(buf, file); |
50 | 0 | } |
51 | | |
52 | 0 | return buf; |
53 | 0 | } |