-
Notifications
You must be signed in to change notification settings - Fork 4
/
fcaseopen.c
115 lines (99 loc) · 1.9 KB
/
fcaseopen.c
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
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
#include "fcaseopen.h"
#if !defined(_WIN32)
#include <stdlib.h>
#include <string.h>
#include <dirent.h>
#include <errno.h>
#include <unistd.h>
// r must have strlen(path) + 3 bytes
static int casepath(char const *path, char *r)
{
size_t l = strlen(path);
char *p = alloca(l + 1);
strcpy(p, path);
size_t rl = 0;
DIR *d;
if (p[0] == '/')
{
d = opendir("/");
p = p + 1;
}
else
{
d = opendir(".");
r[0] = '.';
r[1] = 0;
rl = 1;
}
int last = 0;
char *c = strsep(&p, "/");
while (c)
{
if (!d)
{
return 0;
}
if (last)
{
closedir(d);
return 0;
}
r[rl] = '/';
rl += 1;
r[rl] = 0;
struct dirent *e = readdir(d);
while (e)
{
if (strcasecmp(c, e->d_name) == 0)
{
strcpy(r + rl, e->d_name);
rl += strlen(e->d_name);
closedir(d);
d = opendir(r);
break;
}
e = readdir(d);
}
if (!e)
{
strcpy(r + rl, c);
rl += strlen(c);
last = 1;
}
c = strsep(&p, "/");
}
if (d) closedir(d);
return 1;
}
#endif
FILE *fcaseopen(char const *path, char const *mode)
{
FILE *f = fopen(path, mode);
#if !defined(_WIN32)
if (!f)
{
char *r = alloca(strlen(path) + 3);
if (casepath(path, r))
{
f = fopen(r, mode);
}
}
#endif
return f;
}
void casechdir(char const *path)
{
#if !defined(_WIN32)
char *r = alloca(strlen(path) + 3);
if (casepath(path, r))
{
chdir(r);
}
else
{
errno = ENOENT;
}
#else
chdir(path);
#endif
}