| Line | |
|---|
| 1 | /* A safer version of chdir, which returns back to the
|
|---|
| 2 | initial working directory when the program exits. */
|
|---|
| 3 |
|
|---|
| 4 | #include <errno.h>
|
|---|
| 5 | #include <stdlib.h>
|
|---|
| 6 | #include <unistd.h>
|
|---|
| 7 |
|
|---|
| 8 | static char *initial_wd;
|
|---|
| 9 |
|
|---|
| 10 | static void
|
|---|
| 11 | restore_wd (void)
|
|---|
| 12 | {
|
|---|
| 13 | chdir (initial_wd);
|
|---|
| 14 | }
|
|---|
| 15 |
|
|---|
| 16 | int
|
|---|
| 17 | chdir_safer (char const *dir)
|
|---|
| 18 | {
|
|---|
| 19 | if (! initial_wd)
|
|---|
| 20 | {
|
|---|
| 21 | size_t s;
|
|---|
| 22 | for (s = 256; ! (initial_wd = getcwd (0, s)); s *= 2)
|
|---|
| 23 | if (errno != ERANGE)
|
|---|
| 24 | return -1;
|
|---|
| 25 | if (atexit (restore_wd) != 0)
|
|---|
| 26 | {
|
|---|
| 27 | free (initial_wd);
|
|---|
| 28 | initial_wd = 0;
|
|---|
| 29 | return -1;
|
|---|
| 30 | }
|
|---|
| 31 | }
|
|---|
| 32 |
|
|---|
| 33 | return chdir (dir);
|
|---|
| 34 | }
|
|---|
Note:
See
TracBrowser
for help on using the repository browser.