16 # include <sys/types.h>
19 # include <sys/file.h>
38 char *xgetwd __PROTO((void));
40 /* Record the location of the current working directory in CWD so that
41 the program may change to other directories and later use restore_cwd
42 to return to the recorded location. This function may allocate
43 space using malloc (via xgetwd) or leave a file descriptor open;
44 use free_cwd to perform the necessary free or close. Upon failure,
45 no memory is allocated, any locally opened file descriptors are
46 closed; return non-zero -- in that case, free_cwd need not be
47 called, but doing so is ok. Otherwise, return zero. */
51 struct saved_cwd *cwd;
53 static int have_working_fchdir = 1;
58 if (have_working_fchdir)
61 cwd->desc = open (".", O_RDONLY);
64 error (0, errno, "cannot open current directory");
69 /* On SunOS 4, fchdir returns EINVAL if accounting is enabled,
70 so we have to fall back to chdir. */
71 if (fchdir (cwd->desc))
77 have_working_fchdir = 0;
81 error (0, errno, "current directory");
87 # endif /* __sun__ || sun */
89 #define fchdir(x) (abort (), 0)
90 have_working_fchdir = 0;
94 if (!have_working_fchdir)
96 cwd->name = xgetwd ();
97 if (cwd->name == NULL)
99 error (0, errno, "cannot get current directory");
106 /* Change to recorded location, CWD, in directory hierarchy.
107 If "saved working directory", NULL))
111 restore_cwd (cwd, dest)
112 const struct saved_cwd *cwd;
118 if (fchdir (cwd->desc))
120 error (0, errno, "cannot return to %s",
121 (dest ? dest : "saved working directory"));
125 else if (chdir (cwd->name) < 0)
127 error (0, errno, "%s", cwd->name);
135 struct saved_cwd *cwd;