summaryrefslogtreecommitdiff
path: root/src/lib/evil/evil_libgen.c
blob: d96ba5bae82ab7d35fc75e814d52a55ddac55fde (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
91
92
93
94
95
96
97
98
99
100
#ifdef HAVE_CONFIG_H
# include "config.h"
#endif /* HAVE_CONFIG_H */

#include <string.h>

#include "evil_macro.h"
#include "evil_libgen.h"

char _evil_basename_buf[PATH_MAX];
char _evil_dirname_buf[PATH_MAX];

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

   /* path must begin by "?:\" or "?:/" */
   if ((!path) || !evil_path_is_absolute(path))
     {
        memcpy(_evil_basename_buf, "C:\\", 4);
        return _evil_basename_buf;
     }

   /* '/' --> '\\' */
   length = strlen(path);
   p1 = strdup(path);
   if (!p1)
     {
        memcpy(_evil_basename_buf, "C:\\", 4);
        return _evil_basename_buf;
     }

   EVIL_PATH_SEP_UNIX_TO_WIN32(p1);

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

   p2 = strrchr(p1, '\\');
   memcpy(_evil_basename_buf, p2 + 1, (p1 + length + 1) - p2);

   free(p1);

   return _evil_basename_buf;
}

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

   /* path must begin by "?:\" or "?:/" */
   if ((!path) || !evil_path_is_absolute(path))
     {
        memcpy(_evil_dirname_buf, "C:\\", 4);
        return _evil_dirname_buf;
     }

   /* '/' --> '\\' */
   length = strlen(path);
   p1 = strdup(path);
   if (!p1)
     {
        memcpy(_evil_dirname_buf, "C:\\", 4);
        return _evil_dirname_buf;
     }
   p2 = p1;
   while (*p2)
     {
        if (*p2 == '/') *p2 = '\\';
        p2++;
     }

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

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

   free(p1);

   return _evil_dirname_buf;
}