-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathunixisms.c
61 lines (53 loc) · 1.23 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
/* unixisms.c: Copyright (C) 2011 by Brian Raiter <breadbox@muppetlabs.com>
* License GPLv2+: GNU GPL version 2 or later.
* This is free software; you are free to change and redistribute it.
* There is NO WARRANTY, to the extent permitted by law.
*/
#include <string.h>
#include <unistd.h>
#include <sys/stat.h>
#include <fcntl.h>
#include "unixisms.h"
/* File descriptor of the saved directory.
*/
static int currentdir = -1;
/* Changes the current directory.
*/
int changedir(char const *name)
{
return chdir(name) == 0;
}
/* 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)
{
if (fchdir(currentdir) != 0)
return 0;
close(currentdir);
currentdir = -1;
return 1;
}
/* 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;
}