1 /* listfile.c -- run a function in a specific directory
2 Copyright (C) 2007, 2008, 2009, 2010, 2011 Free Software Foundation,
5 This program is free software: you can redistribute it and/or modify
6 it under the terms of the GNU General Public License as published by
7 the Free Software Foundation, either version 3 of the License, or
8 (at your option) any later version.
10 This program is distributed in the hope that it will be useful,
11 but WITHOUT ANY WARRANTY; without even the implied warranty of
12 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 GNU General Public License for more details.
15 You should have received a copy of the GNU General Public License
16 along with this program. If not, see <http://www.gnu.org/licenses/>.
19 /* This file was written by James Youngman, based on gnulib'c at-func.c.
22 /* config.h must be included first. */
37 #include "dircallback.h"
40 run_in_dir (const struct saved_cwd *there,
41 int (*callback)(void*), void *usercontext)
45 struct saved_cwd here;
46 if (0 == save_cwd (&here))
48 if (0 == restore_cwd (there))
50 err = callback(usercontext);
51 saved_errno = (err < 0 ? errno : 0);
55 openat_restore_fail (errno);
58 if (restore_cwd (&here) != 0)
59 openat_restore_fail (errno);
65 openat_save_fail (errno);
74 run_in_dirfd (int dir_fd, int (*callback)(void*), void *usercontext)
76 if (dir_fd == AT_FDCWD)
78 return (*callback)(usercontext);
82 struct saved_cwd saved_cwd;
86 if (save_cwd (&saved_cwd) != 0)
87 openat_save_fail (errno);
89 if (fchdir (dir_fd) != 0)
92 free_cwd (&saved_cwd);
97 err = (*callback)(usercontext);
98 saved_errno = (err < 0 ? errno : 0);
100 if (restore_cwd (&saved_cwd) != 0)
101 openat_restore_fail (errno);
103 free_cwd (&saved_cwd);