]> diplodocus.org Git - nmh/blob - sbr/pwd.c
Just reworded the bit about '%s' being safe not to quote (it's only safe not to
[nmh] / sbr / pwd.c
1
2 /*
3 * pwd.c -- return the current working directory
4 *
5 * $Id$
6 */
7
8 #include <h/mh.h>
9
10 static char curwd[PATH_MAX];
11
12
13 char *
14 pwd(void)
15 {
16 register char *cp;
17
18 if (!getcwd (curwd, PATH_MAX)) {
19 admonish (NULL, "unable to determine working directory");
20 if (!mypath || !*mypath
21 || (strcpy (curwd, mypath), chdir (curwd)) == -1) {
22 strcpy (curwd, "/");
23 chdir (curwd);
24 }
25 return curwd;
26 }
27
28 if ((cp = curwd + strlen (curwd) - 1) > curwd && *cp == '/')
29 *cp = '\0';
30
31 return curwd;
32 }
33
34
35 #if 0
36
37 /*
38 * Currently commented out. Everyone seems
39 * to have a native version these days.
40 */
41
42 /*
43 * getwd() - get the current working directory
44 */
45
46 int
47 getwd(char *cwd)
48 {
49 int found;
50 char tmp1[BUFSIZ], tmp2[BUFSIZ];
51 struct stat st1, st2, root;
52 register struct direct *dp;
53 register DIR *dd;
54
55 strcpy (cwd, "/");
56 stat ("/", &root);
57
58 for (;;) {
59 if ((dd = opendir ("..")) == NULL)
60 return -1;
61 if (stat (".", &st2) == -1 || stat ("..", &st1) == -1)
62 goto out;
63 if (st2.st_ino == root.st_ino && st2.st_dev == root.st_dev) {
64 closedir (dd);
65 return chdir (cwd);
66 }
67
68 if (st2.st_ino == st1.st_ino && st2.st_dev == st1.st_dev) {
69 closedir (dd);
70 chdir ("/");
71 if ((dd = opendir (".")) == NULL)
72 return -1;
73 if (stat (".", &st1) < 0)
74 goto out;
75 if (st2.st_dev != st1.st_dev)
76 while (dp = readdir (dd)) {
77 if (stat (dp->d_name, &st1) == -1)
78 goto out;
79 if (st2.st_dev == st1.st_dev) {
80 snprintf (tmp1, sizeof(tmp1), "%s%s", dp->d_name, cwd);
81 strcpy (cwd + 1, tmp1);
82 closedir (dd);
83 return (chdir (cwd));
84 }
85 }
86 else {
87 closedir (dd);
88 return (chdir (cwd));
89 }
90 }
91
92 found = 0;
93 while (dp = readdir (dd)) {
94 snprintf (tmp2, sizeof(tmp2), "../%s", dp->d_name);
95 if (stat (tmp2, &st1) != -1
96 && st1.st_ino == st2.st_ino
97 && st1.st_dev == st2.st_dev) {
98 closedir (dd);
99 found++;
100 chdir ("..");
101 snprintf (tmp1, sizeof(tmp1), "%s%s", dp->d_name, cwd);
102 strcpy (cwd + 1, tmp1);
103 break;
104 }
105 }
106 if (!found)
107 goto out;
108 }
109
110 out: ;
111 closedir (dd);
112 return -1;
113 }
114
115 #endif