summaryrefslogtreecommitdiff
path: root/src/lib/escape/escape_libgen.c
blob: 796708978e34bb92581adcbeea13cebd9e8fa289 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
#ifdef HAVE_CONFIG_H
# include "config.h"
#endif /* HAVE_CONFIG_H */

#include <string.h>
#include <malloc.h>

#include "Escape.h"

static char _escape_basename_buf[PATH_MAX];
static char _escape_dirname_buf[PATH_MAX];

char *
escape_basename(char *path)
{
   char *p1;
   char *p2;
   size_t length;

   /* path must begin by "?:\" or "?:/" */
   if (!path || strlen(path) <= 1)
     {
        memcpy(_escape_basename_buf, path, PATH_MAX);
        return _escape_basename_buf;
     }

   length = strlen(path);
   p1 = strdup(path);
   if (!p1)
     {
        memcpy(_escape_basename_buf, path, PATH_MAX);
        return _escape_basename_buf;
     }

   /* remove trailing backslashes */
   p2 = p1 + (length - 1);
   if (*p2 == '/')
     {
        while (*p2 == '/')
          p2--;
     }
   *(p2 + 1) = '\0';

   p2 = strrchr(p1, '/');
   memcpy(_escape_basename_buf, p2 + 1, (p1 + length + 1) - p2);

   free(p1);

   return _escape_basename_buf;
}

char *
escape_dirname(char *path)
{
   char *p1;
   char *p2;
   size_t length;

   /* path must begin by "?:\" or "?:/" */
   if (!path || strlen(path) <= 1)
     {
        memcpy(_escape_dirname_buf, path, PATH_MAX);
        return _escape_dirname_buf;
     }

   length = strlen(path);
   p1 = strdup(path);
   if (!p1)
     {
        memcpy(_escape_dirname_buf, path, PATH_MAX);
        return _escape_dirname_buf;
     }
   /* remove trailing backslashes */
   p2 = p1 + (length - 1);
   if (*p2 == '/')
     {
        while (*p2 == '/')
          p2--;
     }
   *(p2 + 1) = '\0';

   p2 = strrchr(p1, '/');
   *p2 = '\0';
   memcpy(_escape_dirname_buf, p1, strlen(p1) + 1);

   free(p1);

   return _escape_dirname_buf;
}