-
Notifications
You must be signed in to change notification settings - Fork 9
/
Copy pathunixisms.c
118 lines (102 loc) · 2.29 KB
/
unixisms.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
116
117
118
/* unixisms.c: Copyright (C) 2011-2022
* by Brian Raiter <breadbox@muppetlabs.com>
* License GPLv2+: GNU GPL version 2 or later.
*/
#include <stdlib.h>
#include <string.h>
#include <errno.h>
#include <unistd.h>
#include <sys/stat.h>
#include <fcntl.h>
#include "unixisms.h"
/* Changes the current directory.
*/
int changedir(char const *name)
{
return chdir(name) == 0;
}
/* Returns true if the filename is a directory.
*/
int fileisdir(char const *name)
{
struct stat s;
if (stat(name, &s))
return 0;
return S_ISDIR(s.st_mode);
}
/* Returns a pointer to the filename minus any leading directories.
*/
char const *getbasefilename(char const *name)
{
char const *r;
r = strrchr(name, '/');
return r && r[1] ? r + 1 : name;
}
/* The fchdir() function makes savedir() and restoredir() trivial to
* code, but sadly it isn't universal. To maximize portability, a
* fallback version of these functions is provided.
*/
#if _XOPEN_SOURCE >= 500 || _POSIX_C_SOURCE >= 200809L || _BSD_SOURCE
/* File descriptor of the saved directory.
*/
static int currentdir = -1;
/* Opens a file descriptor on the current directory.
*/
int savedir(void)
{
currentdir = open(".", O_RDONLY);
return currentdir >= 0;
}
/* Uses the saved file description to change the directory back.
*/
int restoredir(void)
{
return fchdir(currentdir) == 0;
}
/* Closes the saved directory.
*/
void unsavedir(void)
{
close(currentdir);
currentdir = -1;
}
#else
/* String buffer containing the saved directory.
*/
static char *currentdir = NULL;
static int currentdiralloc = 0;
/* Saves the path to the current directory.
*/
int savedir(void)
{
if (!currentdir) {
currentdiralloc = 256;
currentdir = malloc(currentdiralloc);
if (!currentdir)
return 0;
}
while (!getcwd(currentdir, currentdiralloc)) {
if (errno != ERANGE)
return 0;
currentdiralloc *= 2;
currentdir = realloc(currentdir, currentdiralloc);
if (!currentdir)
return 0;
}
return 1;
}
/* Changes back to the saved directory.
*/
int restoredir(void)
{
return changedir(currentdir);
}
/* Frees the remembered directory.
*/
void unsavedir(void)
{
free(currentdir);
currentdir = NULL;
currentdiralloc = 0;
}
#endif