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