.
[coreutils.git] / lib / rename.c
blob5a158e4cfef951f087f02461f8a46220051ff219
1 /* rename.c -- BSD compatible directory function for System V
2 Copyright (C) 1988, 1990 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 Foundation,
16 Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. */
18 #ifdef HAVE_CONFIG_H
19 #include <config.h>
20 #endif
22 #include <sys/types.h>
23 #include <sys/stat.h>
24 #include <errno.h>
25 #ifndef errno
26 extern int errno;
27 #endif
29 #ifdef STAT_MACROS_BROKEN
30 #undef S_ISDIR
31 #endif /* STAT_MACROS_BROKEN. */
33 #if !defined(S_ISDIR) && defined(S_IFDIR)
34 #define S_ISDIR(m) (((m) & S_IFMT) == S_IFDIR)
35 #endif
37 /* Rename file FROM to file TO.
38 Return 0 if successful, -1 if not. */
40 int
41 rename (from, to)
42 char *from;
43 char *to;
45 struct stat from_stats, to_stats;
46 int pid, status;
48 if (stat (from, &from_stats))
49 return -1;
51 /* Be careful not to unlink `from' if it happens to be equal to `to' or
52 (on filesystems that silently truncate filenames after 14 characters)
53 if `from' and `to' share the significant characters. */
54 if (stat (to, &to_stats))
56 if (errno != ENOENT)
57 return -1;
59 else
61 if ((from_stats.st_dev == to_stats.st_dev)
62 && (from_stats.st_ino == to_stats.st_ino))
63 /* `from' and `to' designate the same file on that filesystem. */
64 return 0;
66 if (unlink (to) && errno != ENOENT)
67 return -1;
70 if (S_ISDIR (from_stats.st_mode))
72 /* Need a setuid root process to link and unlink directories. */
73 pid = fork ();
74 switch (pid)
76 case -1: /* Error. */
77 error (1, errno, "cannot fork");
79 case 0: /* Child. */
80 execl (MVDIR, "mvdir", from, to, (char *) 0);
81 error (255, errno, "cannot run `%s'", MVDIR);
83 default: /* Parent. */
84 while (wait (&status) != pid)
85 /* Do nothing. */ ;
87 errno = 0; /* mvdir printed the system error message. */
88 if (status)
89 return -1;
92 else
94 if (link (from, to))
95 return -1;
96 if (unlink (from) && errno != ENOENT)
98 unlink (to);
99 return -1;
102 return 0;