1 # File/Copy.pm. Written in 1994 by Aaron Sherman <ajs@ajs.com>. This
2 # source code has been placed in the public domain by the author.
3 # Please be kind and preserve the documentation.
5 # Additions copyright 1996 by Charles Bailey. Permission is granted
6 # to distribute the revised code under the same terms as Perl itself.
12 use warnings; no warnings 'newline';
15 # During perl build, we need File::Copy but Scalar::Util might not be built yet
16 # And then we need these games to avoid loading overload, as that will
17 # confuse miniperl during the bootstrap of perl.
18 my $Scalar_Util_loaded = eval q{ require Scalar::Util; require overload; 1 };
19 # We want HiRes stat and utime if available
20 BEGIN { eval q{ use Time::HiRes qw( stat utime ) } };
21 our(@ISA, @EXPORT, @EXPORT_OK, $VERSION, $Too_Big, $Syscopy_is_copy);
31 @EXPORT = qw(copy move);
32 @EXPORT_OK = qw(cp mv);
34 $Too_Big = 1024 * 1024 * 2;
48 if (not defined &basename) {
49 require File::Basename;
50 import File::Basename 'basename';
53 return File::Spec->catfile($to, basename($from));
56 # _eq($from, $to) tells whether $from and $to are identical
58 my ($from, $to) = map {
59 $Scalar_Util_loaded && Scalar::Util::blessed($_)
60 && overload::Method($_, q{""})
64 return '' if ( (ref $from) xor (ref $to) );
65 return $from == $to if ref $from;
70 croak("Usage: copy(FROM, TO [, BUFFERSIZE]) ")
71 unless(@_ == 2 || @_ == 3);
78 $size = shift(@_) + 0;
79 croak("Bad buffer size for copy: $size\n") unless ($size > 0);
82 my $from_a_handle = (ref($from)
83 ? (ref($from) eq 'GLOB'
84 || UNIVERSAL::isa($from, 'GLOB')
85 || UNIVERSAL::isa($from, 'IO::Handle'))
86 : (ref(\$from) eq 'GLOB'));
87 my $to_a_handle = (ref($to)
89 || UNIVERSAL::isa($to, 'GLOB')
90 || UNIVERSAL::isa($to, 'IO::Handle'))
91 : (ref(\$to) eq 'GLOB'));
93 if (_eq($from, $to)) { # works for references, too
94 carp("'$from' and '$to' are identical (not copied)");
98 if (!$from_a_handle && !$to_a_handle && -d $to && ! -d $from) {
99 $to = _catname($from, $to);
102 if ((($Config{d_symlink} && $Config{d_readlink}) || $Config{d_link}) &&
103 !($^O eq 'MSWin32' || $^O eq 'os2')) {
104 my @fs = stat($from);
107 if (@ts && $fs[0] == $ts[0] && $fs[1] == $ts[1] && !-p $from) {
108 carp("'$from' and '$to' are identical (not copied)");
113 elsif (_eq($from, $to)) {
114 carp("'$from' and '$to' are identical (not copied)");
118 if (defined &syscopy && !$Syscopy_is_copy
120 && !($from_a_handle && $^O eq 'os2' ) # OS/2 cannot handle handles
121 && !($from_a_handle && $^O eq 'MSWin32')
122 && !($from_a_handle && $^O eq 'NetWare')
125 if ($^O eq 'VMS' && -e $from
126 && ! -d $to && ! -d $from) {
128 # VMS natively inherits path components from the source of a
129 # copy, but we want the Unixy behavior of inheriting from
130 # the current working directory. Also, default in a trailing
131 # dot for null file types.
133 $to = VMS::Filespec::rmsexpand(VMS::Filespec::vmsify($to), '.');
135 # Get rid of the old versions to be like UNIX
139 return syscopy($from, $to) || 0;
144 my ($status, $r, $buf);
148 if ($from_a_handle) {
151 open $from_h, "<", $from or goto fail_open1;
152 binmode $from_h or die "($!,$^E)";
156 # Seems most logical to do this here, in case future changes would want to
157 # make this croak for some reason.
158 unless (defined $size) {
159 $size = tied(*$from_h) ? 0 : -s $from_h || 0;
160 $size = 1024 if ($size < 512);
161 $size = $Too_Big if ($size > $Too_Big);
168 $to_h = \do { local *FH }; # XXX is this line obsolete?
169 open $to_h, ">", $to or goto fail_open2;
170 binmode $to_h or die "($!,$^E)";
177 defined($r = sysread($from_h, $buf, $size))
180 for ($w = 0; $w < $r; $w += $t) {
181 $t = syswrite($to_h, $buf, $r - $w, $w)
186 close($to_h) || goto fail_open2 if $closeto;
187 close($from_h) || goto fail_open1 if $closefrom;
189 # Use this idiom to avoid uninitialized value warning.
192 # All of these contortions try to preserve error messages...
198 $! = $status unless $!;
205 $! = $status unless $!;
213 my(@fromstat) = stat $from;
214 my(@tostat) = stat $to;
217 return 0 unless copy(@_) and @fromstat;
222 $perm = $fromstat[2] & ~(umask || 0);
225 # Might be more robust to look for S_I* in Fcntl, but we're
226 # trying to avoid dependence on any XS-containing modules,
227 # since File::Copy is used during the Perl build.
230 croak("Unable to check setuid/setgid permissions for $to: $!")
233 if ($perm & 04000 and # setuid
234 $fromstat[4] != $tostat[4]) { # owner must match
238 if ($perm & 02000 && $> != 0) { # if not root, setgid
239 my $ok = $fromstat[5] == $tostat[5]; # group must match
240 if ($ok) { # and we must be in group
241 $ok = grep { $_ == $fromstat[5] } split /\s+/, $)
243 $perm &= ~06000 unless $ok;
246 return 0 unless @tostat;
247 return 1 if $perm == ($tostat[2] & 07777);
248 return eval { chmod $perm, $to; } ? 1 : 0;
252 croak("Usage: move(FROM, TO) ") unless @_ == 3;
254 my($from,$to,$fallback) = @_;
256 my($fromsz,$tosz1,$tomt1,$tosz2,$tomt2,$sts,$ossts);
258 if (-d $to && ! -d $from) {
259 $to = _catname($from, $to);
262 ($tosz1,$tomt1) = (stat($to))[7,9];
264 if ($^O eq 'os2' and defined $tosz1 and defined $fromsz) {
265 # will not rename with overwrite
269 if ($^O eq 'VMS' && -e $from
270 && ! -d $to && ! -d $from) {
272 # VMS natively inherits path components from the source of a
273 # copy, but we want the Unixy behavior of inheriting from
274 # the current working directory. Also, default in a trailing
275 # dot for null file types.
277 $to = VMS::Filespec::rmsexpand(VMS::Filespec::vmsify($to), '.');
279 # Get rid of the old versions to be like UNIX
283 return 1 if rename $from, $to;
285 # Did rename return an error even though it succeeded, because $to
286 # is on a remote NFS file system, and NFS lost the server's ack?
287 return 1 if defined($fromsz) && !-e $from && # $from disappeared
288 (($tosz2,$tomt2) = (stat($to))[7,9]) && # $to's there
289 ((!defined $tosz1) || # not before or
290 ($tosz1 != $tosz2 or $tomt1 != $tomt2)) && # was changed
291 $tosz2 == $fromsz; # it's all there
293 ($tosz1,$tomt1) = (stat($to))[7,9]; # just in case rename did something
299 $fallback->($from,$to) or die;
300 my($atime, $mtime) = (stat($from))[8,9];
301 utime($atime, $mtime, $to);
302 unlink($from) or die;
306 ($sts,$ossts) = ($! + 0, $^E + 0);
308 ($tosz2,$tomt2) = ((stat($to))[7,9],0,0) if defined $tomt1;
309 unlink($to) if !defined($tomt1) or $tomt1 != $tomt2 or $tosz1 != $tosz2;
310 ($!,$^E) = ($sts,$ossts);
314 sub move { _move(@_,\©); }
315 sub mv { _move(@_,\&cp); }
317 # &syscopy is an XSUB under OS/2
318 unless (defined &syscopy) {
320 *syscopy = \&rmscopy;
321 } elsif ($^O eq 'MSWin32' && defined &DynaLoader::boot_DynaLoader) {
322 # Win32::CopyFile() fill only work if we can load Win32.xs
324 return 0 unless @_ == 2;
325 return Win32::CopyFile(@_, 1);
328 $Syscopy_is_copy = 1;
339 File::Copy - Copy files or filehandles
345 copy("sourcefile","destinationfile") or die "Copy failed: $!";
346 copy("Copy.pm",\*STDOUT);
347 move("/dev1/sourcefile","/dev2/destinationfile");
351 $n = FileHandle->new("/a/file","r");
356 The File::Copy module provides two basic functions, C<copy> and
357 C<move>, which are useful for getting the contents of a file from
358 one place to another.
365 The C<copy> function takes two
366 parameters: a file to copy from and a file to copy to. Either
367 argument may be a string, a FileHandle reference or a FileHandle
368 glob. Obviously, if the first argument is a filehandle of some
369 sort, it will be read from, and if it is a file I<name> it will
370 be opened for reading. Likewise, the second argument will be
371 written to. If the second argument does not exist but the parent
372 directory does exist, then it will be created. Trying to copy
373 a file into a non-existent directory is an error.
374 Trying to copy a file on top of itself is also an error.
375 C<copy> will not overwrite read-only files.
377 If the destination (second argument) already exists and is a directory,
378 and the source (first argument) is not a filehandle, then the source
379 file will be copied into the directory specified by the destination,
380 using the same base name as the source file. It's a failure to have a
381 filehandle as the source when the destination is a directory.
383 B<Note that passing in
384 files as handles instead of names may lead to loss of information
385 on some operating systems; it is recommended that you use file
386 names whenever possible.> Files are opened in binary mode where
387 applicable. To get a consistent behaviour when copying from a
388 filehandle to a file, use C<binmode> on the filehandle.
390 An optional third parameter can be used to specify the buffer
391 size used for copying. This is the number of bytes from the
392 first file, that will be held in memory at any given time, before
393 being written to the second file. The default buffer size depends
394 upon the file, but will generally be the whole file (up to 2MB), or
395 1k for filehandles that do not reference files (eg. sockets).
397 You may use the syntax C<use File::Copy "cp"> to get at the C<cp>
398 alias for this function. The syntax is I<exactly> the same. The
399 behavior is nearly the same as well: as of version 2.15, C<cp> will
400 preserve the source file's permission bits like the shell utility
401 C<cp(1)> would do, while C<copy> uses the default permissions for the
402 target file (which may depend on the process' C<umask>, file
403 ownership, inherited ACLs, etc.). If an error occurs in setting
404 permissions, C<cp> will return 0, regardless of whether the file was
408 X<move> X<mv> X<rename>
410 The C<move> function also takes two parameters: the current name
411 and the intended name of the file to be moved. If the destination
412 already exists and is a directory, and the source is not a
413 directory, then the source file will be renamed into the directory
414 specified by the destination.
416 If possible, move() will simply rename the file. Otherwise, it copies
417 the file to the new location and deletes the original. If an error occurs
418 during this copy-and-delete process, you may be left with a (possibly partial)
419 copy of the file under the destination name.
421 You may use the C<mv> alias for this function in the same way that
422 you may use the C<cp> alias for C<copy>.
427 File::Copy also provides the C<syscopy> routine, which copies the
428 file specified in the first parameter to the file specified in the
429 second parameter, preserving OS-specific attributes and file
430 structure. For Unix systems, this is equivalent to the simple
431 C<copy> routine, which doesn't preserve OS-specific attributes. For
432 VMS systems, this calls the C<rmscopy> routine (see below). For OS/2
433 systems, this calls the C<syscopy> XSUB directly. For Win32 systems,
434 this calls C<Win32::CopyFile>.
436 B<Special behaviour if C<syscopy> is defined (OS/2, VMS and Win32)>:
438 If both arguments to C<copy> are not file handles,
439 then C<copy> will perform a "system copy" of
440 the input file to a new output file, in order to preserve file
441 attributes, indexed file structure, I<etc.> The buffer size
442 parameter is ignored. If either argument to C<copy> is a
443 handle to an opened file, then data is copied using Perl
444 operators, and no effort is made to preserve file attributes
447 The system copy routine may also be called directly under VMS and OS/2
448 as C<File::Copy::syscopy> (or under VMS as C<File::Copy::rmscopy>, which
449 is the routine that does the actual work for syscopy).
451 =item rmscopy($from,$to[,$date_flag])
454 The first and second arguments may be strings, typeglobs, typeglob
455 references, or objects inheriting from IO::Handle;
456 they are used in all cases to obtain the
457 I<filespec> of the input and output files, respectively. The
458 name and type of the input file are used as defaults for the
459 output file, if necessary.
461 A new version of the output file is always created, which
462 inherits the structure and RMS attributes of the input file,
463 except for owner and protections (and possibly timestamps;
464 see below). All data from the input file is copied to the
465 output file; if either of the first two parameters to C<rmscopy>
466 is a file handle, its position is unchanged. (Note that this
467 means a file handle pointing to the output file will be
468 associated with an old version of that file after C<rmscopy>
469 returns, not the newly created version.)
471 The third parameter is an integer flag, which tells C<rmscopy>
472 how to handle timestamps. If it is E<lt> 0, none of the input file's
473 timestamps are propagated to the output file. If it is E<gt> 0, then
474 it is interpreted as a bitmask: if bit 0 (the LSB) is set, then
475 timestamps other than the revision date are propagated; if bit 1
476 is set, the revision date is propagated. If the third parameter
477 to C<rmscopy> is 0, then it behaves much like the DCL COPY command:
478 if the name or type of the output file was explicitly specified,
479 then no timestamps are propagated, but if they were taken implicitly
480 from the input filespec, then all timestamps other than the
481 revision date are propagated. If this parameter is not supplied,
484 C<rmscopy> is VMS specific and cannot be exported; it must be
485 referenced by its full name, e.g.:
487 File::Copy::rmscopy($from, $to) or die $!;
489 Like C<copy>, C<rmscopy> returns 1 on success. If an error occurs,
490 it sets C<$!>, deletes the output file, and returns 0.
496 All functions return 1 on success, 0 on failure.
497 $! will be set if an error was encountered.
501 Before calling copy() or move() on a filehandle, the caller should
502 close or flush() the file to avoid writes being lost. Note that this
503 is the case even for move(), because it may actually copy the file,
504 depending on the OS-specific implementation, and the underlying
509 File::Copy was written by Aaron Sherman I<E<lt>ajs@ajs.comE<gt>> in 1995,
510 and updated by Charles Bailey I<E<lt>bailey@newman.upenn.eduE<gt>> in 1996.