cvsimport
[findutils.git] / lib / dircallback.c
blob29fb276c84d3302453ce7ed32d9c35be93652a99
1 /* listfile.c -- run a function in a specific directory
2 Copyright (C) 2007, 2008 Free Software Foundation, Inc.
4 This program is free software: you can redistribute it and/or modify
5 it under the terms of the GNU General Public License as published by
6 the Free Software Foundation, either version 3 of the License, or
7 (at your option) any later version.
9 This program is distributed in the hope that it will be useful,
10 but WITHOUT ANY WARRANTY; without even the implied warranty of
11 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12 GNU General Public License for more details.
14 You should have received a copy of the GNU General Public License
15 along with this program. If not, see <http://www.gnu.org/licenses/>.
18 /* This file was written by James Youngman, based on gnulib'c at-func.c.
22 #include <config.h>
25 #include "openat.h"
26 #include <stdarg.h>
27 #include <stddef.h>
28 #include <errno.h>
30 #include "fcntl--.h"
31 #include "lstat.h"
32 #include "save-cwd.h"
35 /* The presence of unistd.h is assumed by gnulib these days, so we
36 * might as well assume it too.
38 #include <unistd.h> /* for readlink() */
40 #ifdef HAVE_LOCALE_H
41 #include <locale.h>
42 #endif
44 #if ENABLE_NLS
45 # include <libintl.h>
46 # define _(Text) gettext (Text)
47 #else
48 # define _(Text) Text
49 #define textdomain(Domain)
50 #define bindtextdomain(Package, Directory)
51 #endif
52 #ifdef gettext_noop
53 # define N_(String) gettext_noop (String)
54 #else
55 /* See locate.c for explanation as to why not use (String) */
56 # define N_(String) String
57 #endif
61 int
62 run_in_dir (int dir_fd, int (*callback)(void*), void *usercontext)
64 if (dir_fd == AT_FDCWD)
66 return (*callback)(usercontext);
68 else
70 struct saved_cwd saved_cwd;
71 int saved_errno;
72 int err;
74 if (save_cwd (&saved_cwd) != 0)
75 openat_save_fail (errno);
77 if (fchdir (dir_fd) != 0)
79 saved_errno = errno;
80 free_cwd (&saved_cwd);
81 errno = saved_errno;
82 return -1;
85 err = (*callback)(usercontext);
86 saved_errno = (err < 0 ? errno : 0);
88 if (restore_cwd (&saved_cwd) != 0)
89 openat_restore_fail (errno);
91 free_cwd (&saved_cwd);
93 if (saved_errno)
94 errno = saved_errno;
95 return err;