2 Copyright (C) 2001-2003, 2006-2007, 2009-2011 Free Software Foundation, Inc.
3 Written by Bruno Haible <haible@clisp.cons.org>, 2001.
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/>. */
22 #include "copy-file.h"
31 #if HAVE_UTIME || HAVE_UTIMES
35 # include <sys/utime.h>
40 #include "safe-read.h"
41 #include "full-write.h"
43 #include "binary-io.h"
47 #define _(str) gettext (str)
49 /* The results of open() in this file are not used with fchdir,
50 therefore save some unnecessary work in fchdir.c. */
54 enum { IO_SIZE = 32 * 1024 };
57 copy_file_preserving (const char *src_filename, const char *dest_filename)
63 char *buf = xmalloc (IO_SIZE);
65 src_fd = open (src_filename, O_RDONLY | O_BINARY);
66 if (src_fd < 0 || fstat (src_fd, &statbuf) < 0)
67 error (EXIT_FAILURE, errno, _("error while opening \"%s\" for reading"),
70 mode = statbuf.st_mode & 07777;
72 dest_fd = open (dest_filename, O_WRONLY | O_CREAT | O_TRUNC | O_BINARY, 0600);
74 error (EXIT_FAILURE, errno, _("cannot open backup file \"%s\" for writing"),
77 /* Copy the file contents. */
80 size_t n_read = safe_read (src_fd, buf, IO_SIZE);
81 if (n_read == SAFE_READ_ERROR)
82 error (EXIT_FAILURE, errno, _("error reading \"%s\""), src_filename);
86 if (full_write (dest_fd, buf, n_read) < n_read)
87 error (EXIT_FAILURE, errno, _("error writing \"%s\""), dest_filename);
93 if (close (dest_fd) < 0)
94 error (EXIT_FAILURE, errno, _("error writing \"%s\""), dest_filename);
95 if (close (src_fd) < 0)
96 error (EXIT_FAILURE, errno, _("error after reading \"%s\""), src_filename);
99 /* Preserve the access and modification times. */
104 ut.actime = statbuf.st_atime;
105 ut.modtime = statbuf.st_mtime;
106 utime (dest_filename, &ut);
110 struct timeval ut[2];
112 ut[0].tv_sec = statbuf.st_atime; ut[0].tv_usec = 0;
113 ut[1].tv_sec = statbuf.st_mtime; ut[1].tv_usec = 0;
114 utimes (dest_filename, &ut);
119 /* Preserve the owner and group. */
120 chown (dest_filename, statbuf.st_uid, statbuf.st_gid);
123 /* Preserve the access permissions. */
125 if (copy_acl (src_filename, src_fd, dest_filename, dest_fd, mode))
128 chmod (dest_filename, mode);
132 if (close (dest_fd) < 0)
133 error (EXIT_FAILURE, errno, _("error writing \"%s\""), dest_filename);
134 if (close (src_fd) < 0)
135 error (EXIT_FAILURE, errno, _("error after reading \"%s\""), src_filename);