GNU file utilities
[gnulib.git] / lib / rename.c
1 /* rename.c -- BSD compatible directory function for System V
2    Copyright (C) 1988, 1990 Free Software Foundation, Inc.
3
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.
8
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.
13
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., 675 Mass Ave, Cambridge, MA 02139, USA.  */
17
18 #include <sys/types.h>
19 #include <sys/stat.h>
20 #include <errno.h>
21 #ifndef STDC_HEADERS
22 extern int errno;
23 #endif
24
25 #if !defined(S_ISDIR) && defined(S_IFDIR)
26 #define S_ISDIR(m) (((m) & S_IFMT) == S_IFDIR)
27 #endif
28
29 /* Rename file FROM to file TO.
30    Return 0 if successful, -1 if not. */
31
32 int
33 rename (from, to)
34      char *from;
35      char *to;
36 {
37   struct stat from_stats, to_stats;
38   int pid, status;
39
40   if (stat (from, &from_stats))
41     return -1;
42
43   /* Be careful not to unlink `from' if it happens to be equal to `to' or
44      (on filesystems that silently truncate filenames after 14 characters)
45      if `from' and `to' share the significant characters. */
46   if (stat (to, &to_stats))
47     {
48       if (errno != ENOENT)
49         return -1;
50     }
51   else
52     {
53       if ((from_stats.st_dev == to_stats.st_dev)
54           && (from_stats.st_ino == to_stats.st_dev))
55         /* `from' and `to' designate the same file on that filesystem. */
56         return 0;
57
58       if (unlink (to) && errno != ENOENT)
59         return -1;
60     }
61
62   if (S_ISDIR (from_stats.st_mode))
63     {
64       /* Need a setuid root process to link and unlink directories. */
65       pid = fork ();
66       switch (pid)
67         {
68         case -1:                /* Error. */
69           error (1, errno, "cannot fork");
70
71         case 0:                 /* Child. */
72           execl (MVDIR, "mvdir", from, to, (char *) 0);
73           error (255, errno, "cannot run `%s'", MVDIR);
74
75         default:                /* Parent. */
76           while (wait (&status) != pid)
77             /* Do nothing. */ ;
78
79           errno = 0;            /* mvdir printed the system error message. */
80           if (status)
81             return -1;
82         }
83     }
84   else
85     {
86       if (link (from, to))
87         return -1;
88       if (unlink (from) && errno != ENOENT)
89         {
90           unlink (to);
91           return -1;
92         }
93     }
94   return 0;
95 }