cvsimport
[findutils.git] / lib / dircallback.c
blob81253b93134f63406d38da4bf3942b411731e8b2
1 /* listfile.c -- run a function in a specific directory
2 Copyright (C) 2007 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 2, or (at your option)
7 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, write to the Free Software
16 Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301,
17 USA.
20 /* This file was written by James Youngman, based on gnulib'c at-func.c.
24 #if HAVE_CONFIG_H
25 # include <config.h>
26 #endif
28 #include "openat.h"
29 #include <stdarg.h>
30 #include <stddef.h>
32 #include "fcntl--.h"
33 #include "lchown.h"
34 #include "lstat.h"
35 #include "save-cwd.h"
38 /* The presence of unistd.h is assumed by gnulib these days, so we
39 * might as well assume it too.
41 #include <unistd.h> /* for readlink() */
43 #ifdef HAVE_LOCALE_H
44 #include <locale.h>
45 #endif
47 #if ENABLE_NLS
48 # include <libintl.h>
49 # define _(Text) gettext (Text)
50 #else
51 # define _(Text) Text
52 #define textdomain(Domain)
53 #define bindtextdomain(Package, Directory)
54 #endif
55 #ifdef gettext_noop
56 # define N_(String) gettext_noop (String)
57 #else
58 /* See locate.c for explanation as to why not use (String) */
59 # define N_(String) String
60 #endif
64 int
65 run_in_dir (int dirfd, int (*callback)(void*), void *usercontext)
67 if (dirfd == AT_FDCWD)
69 return (*callback)(usercontext);
71 else
73 struct saved_cwd saved_cwd;
74 int saved_errno;
75 int err;
77 if (save_cwd (&saved_cwd) != 0)
78 openat_save_fail (errno);
80 if (fchdir (dirfd) != 0)
82 saved_errno = errno;
83 free_cwd (&saved_cwd);
84 errno = saved_errno;
85 return -1;
88 err = (*callback)(usercontext);
89 saved_errno = (err < 0 ? errno : 0);
91 if (restore_cwd (&saved_cwd) != 0)
92 openat_restore_fail (errno);
94 free_cwd (&saved_cwd);
96 if (saved_errno)
97 errno = saved_errno;
98 return err;