18 # include <sys/file.h>
37 char *xgetwd __PROTO((void));
39 /* Record the location of the current working directory in CWD so that
40 the program may change to other directories and later use restore_cwd
41 to return to the recorded location. This function may allocate
42 space using malloc (via xgetwd) or leave a file descriptor open;
43 use free_cwd to perform the necessary free or close. Upon failure,
44 no memory is allocated, any locally opened file descriptors are
45 closed; return non-zero -- in that case, free_cwd need not be
46 called, but doing so is ok. Otherwise, return zero. */
50 struct saved_cwd *cwd;
52 static int have_working_fchdir = 1;
57 if (have_working_fchdir)
60 cwd->desc = open (".", O_RDONLY);
63 error (0, errno, "cannot open current directory");
68 /* On SunOS 4, fchdir returns EINVAL if accounting is enabled,
69 so we have to fall back to chdir. */
70 if (fchdir (cwd->desc))
76 have_working_fchdir = 0;
80 error (0, errno, "current directory");
86 # endif /* __sun__ || sun */
88 #define fchdir(x) (abort (), 0)
89 have_working_fchdir = 0;
93 if (!have_working_fchdir)
95 cwd->name = xgetwd ();
96 if (cwd->name == NULL)
98 error (0, errno, "cannot get current directory");
105 /* Change to recorded location, CWD, in directory hierarchy.
106 If "saved working directory", NULL))
110 restore_cwd (cwd, dest)
111 const struct saved_cwd *cwd;
117 if (fchdir (cwd->desc))
119 error (0, errno, "cannot return to %s",
120 (dest ? dest : "saved working directory"));
124 else if (chdir (cwd->name) < 0)
126 error (0, errno, "%s", cwd->name);
134 struct saved_cwd *cwd;