2 Copyright (C) 2001-2003, 2006 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 2, or (at your option)
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, write to the Free Software Foundation,
17 Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */
25 #include "copy-file.h"
33 #if HAVE_UTIME || HAVE_UTIMES
37 # include <sys/utime.h>
42 #include "safe-read.h"
43 #include "full-write.h"
44 #include "binary-io.h"
48 #define _(str) gettext (str)
51 copy_file_preserving (const char *src_filename, const char *dest_filename)
58 const size_t buf_size = sizeof (buf);
60 src_fd = open (src_filename, O_RDONLY | O_BINARY);
61 if (src_fd < 0 || fstat (src_fd, &statbuf) < 0)
62 error (EXIT_FAILURE, errno, _("error while opening \"%s\" for reading"),
65 mode = statbuf.st_mode & 07777;
67 dest_fd = open (dest_filename, O_WRONLY | O_CREAT | O_TRUNC | O_BINARY, 0600);
69 error (EXIT_FAILURE, errno, _("cannot open backup file \"%s\" for writing"),
72 /* Copy the file contents. */
75 size_t n_read = safe_read (src_fd, buf, buf_size);
76 if (n_read == SAFE_READ_ERROR)
77 error (EXIT_FAILURE, errno, _("error reading \"%s\""), src_filename);
81 if (full_write (dest_fd, buf, n_read) < n_read)
82 error (EXIT_FAILURE, errno, _("error writing \"%s\""), dest_filename);
85 if (close (dest_fd) < 0)
86 error (EXIT_FAILURE, errno, _("error writing \"%s\""), dest_filename);
87 if (close (src_fd) < 0)
88 error (EXIT_FAILURE, errno, _("error after reading \"%s\""), src_filename);
90 /* Preserve the access and modification times. */
95 ut.actime = statbuf.st_atime;
96 ut.modtime = statbuf.st_mtime;
97 utime (dest_filename, &ut);
101 struct timeval ut[2];
103 ut[0].tv_sec = statbuf.st_atime; ut[0].tv_usec = 0;
104 ut[1].tv_sec = statbuf.st_mtime; ut[1].tv_usec = 0;
105 utimes (dest_filename, &ut);
110 /* Preserve the owner and group. */
111 chown (dest_filename, statbuf.st_uid, statbuf.st_gid);
114 /* Preserve the access permissions. */
115 chmod (dest_filename, mode);