2 $VERSION = $VERSION = '3.01';
6 Cwd - get pathname of current working directory
14 my $abs_path = abs_path($file);
18 This module provides functions for determining the pathname of the
19 current working directory. It is recommended that getcwd (or another
20 *cwd() function) be used in I<all> code to ensure portability.
22 By default, it exports the functions cwd(), getcwd(), fastcwd(), and
23 fastgetcwd() (and, on Win32, getdcwd()) into the caller's namespace.
26 =head2 getcwd and friends
28 Each of these functions are called without arguments and return the
29 absolute path of the current working directory.
37 Returns the current working directory.
39 Re-implements the getcwd(3) (or getwd(3)) functions in Perl.
45 The cwd() is the most natural form for the current architecture. For
46 most systems it is identical to `pwd` (but without the trailing line
53 A more dangerous version of getcwd(), but potentially faster.
55 It might conceivably chdir() you out of a directory that it can't
56 chdir() you back into. If fastcwd encounters a problem it will return
57 undef but will probably leave you in a different directory. For a
58 measure of extra security, if everything appears to have worked, the
59 fastcwd() function will check that it leaves you in the same directory
60 that it started in. If it has changed it will C<die> with the message
61 "Unstable directory path, current directory changed
62 unexpectedly". That should never happen.
66 my $cwd = fastgetcwd();
68 The fastgetcwd() function is provided as a synonym for cwd().
73 my $cwd = getdcwd('C:');
75 The getdcwd() function is also provided on Win32 to get the current working
76 directory on the specified drive, since Windows maintains a separate current
77 working directory for each drive. If no drive is specified then the current
80 This function simply calls the Microsoft C library _getdcwd() function.
85 =head2 abs_path and friends
87 These functions are exported only on request. They each take a single
88 argument and return the absolute pathname for it. If no argument is
89 given they'll use the current working directory.
95 my $abs_path = abs_path($file);
97 Uses the same algorithm as getcwd(). Symbolic links and relative-path
98 components ("." and "..") are resolved to return the canonical
99 pathname, just like realpath(3).
103 my $abs_path = realpath($file);
105 A synonym for abs_path().
109 my $abs_path = fast_abs_path($file);
111 A more dangerous, but potentially faster version of abs_path.
117 If you ask to override your chdir() built-in function,
121 then your PWD environment variable will be kept up to date. Note that
122 it will only be kept up to date if all packages which use chdir import
132 Since the path seperators are different on some operating systems ('/'
133 on Unix, ':' on MacPerl, etc...) we recommend you use the File::Spec
134 modules wherever portability is a concern.
138 Actually, on Mac OS, the C<getcwd()>, C<fastgetcwd()> and C<fastcwd()>
139 functions are all aliases for the C<cwd()> function, which, on Mac OS,
140 calls `pwd`. Likewise, the C<abs_path()> function is an alias for
147 Originally by the perl5-porters.
149 Maintained by Ken Williams <KWILLIAMS@cpan.org>
159 use vars qw(@ISA @EXPORT @EXPORT_OK);
161 @ISA = qw/ Exporter /;
162 @EXPORT = qw(cwd getcwd fastcwd fastgetcwd);
163 push @EXPORT, qw(getdcwd) if $^O eq 'MSWin32';
164 @EXPORT_OK = qw(chdir abs_path fast_abs_path realpath fast_realpath);
166 # sys_cwd may keep the builtin command
168 # All the functionality of this module may provided by builtins,
169 # there is no sense to process the rest of the file.
170 # The best choice may be to have this in BEGIN, but how to return from BEGIN?
175 *cwd = defined &sys_cwd ? \&sys_cwd : \&_os2_cwd;
180 *fast_abs_path = \&sys_abspath if defined &sys_abspath;
181 *abs_path = \&fast_abs_path;
182 *realpath = \&fast_abs_path;
183 *fast_realpath = \&fast_abs_path;
191 XSLoader::load('Cwd');
194 # Big nasty table of function aliases
200 getcwd => '_vms_cwd',
201 fastcwd => '_vms_cwd',
202 fastgetcwd => '_vms_cwd',
203 abs_path => '_vms_abs_path',
204 fast_abs_path => '_vms_abs_path',
209 # We assume that &_NT_cwd is defined as an XSUB or in the core.
212 fastcwd => '_NT_cwd',
213 fastgetcwd => '_NT_cwd',
214 abs_path => 'fast_abs_path',
215 realpath => 'fast_abs_path',
221 getcwd => '_dos_cwd',
222 fastgetcwd => '_dos_cwd',
223 fastcwd => '_dos_cwd',
224 abs_path => 'fast_abs_path',
230 getcwd => '_qnx_cwd',
231 fastgetcwd => '_qnx_cwd',
232 fastcwd => '_qnx_cwd',
233 abs_path => '_qnx_abs_path',
234 fast_abs_path => '_qnx_abs_path',
242 abs_path => 'fast_abs_path',
243 realpath => 'fast_abs_path',
249 getcwd => '_epoc_cwd',
250 fastgetcwd => '_epoc_cwd',
251 fastcwd => '_epoc_cwd',
252 abs_path => 'fast_abs_path',
260 abs_path => 'fast_abs_path',
264 $METHOD_MAP{NT} = $METHOD_MAP{MSWin32};
265 $METHOD_MAP{nto} = $METHOD_MAP{qnx};
268 # Find the pwd command in the expected locations. We assume these
269 # are safe. This prevents _backtick_pwd() consulting $ENV{PATH}
270 # so everything works under taint mode.
272 foreach my $try ('/bin/pwd',
274 '/QOpenSys/bin/pwd', # OS/400 PASE.
283 # Isn't this wrong? _backtick_pwd() will fail if somenone has
284 # pwd in their path but it is not /bin/pwd or /usr/bin/pwd?
285 # See [perl #16774]. --jhi
290 sub _carp { require Carp; Carp::carp(@_) }
291 sub _croak { require Carp; Carp::croak(@_) }
293 # The 'natural and safe form' for UNIX (pwd may be setuid root)
295 local @ENV{qw(PATH IFS CDPATH ENV BASH_ENV)};
296 my $cwd = `$pwd_cmd`;
297 # Belt-and-suspenders in case someone said "undef $/".
299 # `pwd` may fail e.g. if the disk is full
300 chomp($cwd) if defined $cwd;
304 # Since some ports may predefine cwd internally (e.g., NT)
305 # we take care not to override an existing definition for cwd().
307 unless ($METHOD_MAP{$^O}{cwd} or defined &cwd) {
308 # The pwd command is not available in some chroot(2)'ed environments
309 my $sep = $Config::Config{path_sep} || ':';
310 if( $^O eq 'MacOS' || (defined $ENV{PATH} &&
311 grep { -x "$_/pwd" } split($sep, $ENV{PATH})) )
313 *cwd = \&_backtick_pwd;
320 # set a reasonable (and very safe) default for fastgetcwd, in case it
321 # isn't redefined later (20001212 rspier)
324 # By Brandon S. Allbery
326 # Usage: $cwd = getcwd();
336 # Usage: $cwd = &fastcwd;
338 # This is a faster version of getcwd. It's also more dangerous because
339 # you might chdir out of a directory that you can't chdir back into.
342 my($odev, $oino, $cdev, $cino, $tdev, $tino);
346 my($orig_cdev, $orig_cino) = stat('.');
347 ($cdev, $cino) = ($orig_cdev, $orig_cino);
350 ($odev, $oino) = ($cdev, $cino);
351 CORE::chdir('..') || return undef;
352 ($cdev, $cino) = stat('.');
353 last if $odev == $cdev && $oino == $cino;
354 opendir(DIR, '.') || return undef;
356 $direntry = readdir(DIR);
357 last unless defined $direntry;
358 next if $direntry eq '.';
359 next if $direntry eq '..';
361 ($tdev, $tino) = lstat($direntry);
362 last unless $tdev != $odev || $tino != $oino;
365 return undef unless defined $direntry; # should never happen
366 unshift(@path, $direntry);
368 $path = '/' . join('/', @path);
369 if ($^O eq 'apollo') { $path = "/".$path; }
370 # At this point $path may be tainted (if tainting) and chdir would fail.
371 # Untaint it then check that we landed where we started.
372 $path =~ /^(.*)\z/s # untaint
373 && CORE::chdir($1) or return undef;
374 ($cdev, $cino) = stat('.');
375 die "Unstable directory path, current directory changed unexpectedly"
376 if $cdev != $orig_cdev || $cino != $orig_cino;
381 # Keeps track of current working directory in PWD environment var
389 if ($ENV{'PWD'} and $^O ne 'os2' and $^O ne 'dos' and $^O ne 'MSWin32') {
390 my($dd,$di) = stat('.');
391 my($pd,$pi) = stat($ENV{'PWD'});
392 if (!defined $dd or !defined $pd or $di != $pi or $dd != $pd) {
398 $wd = Win32::GetFullPathName($wd) if $^O eq 'MSWin32';
401 # Strip an automounter prefix (where /tmp_mnt/foo/bar == /foo/bar)
402 if ($^O ne 'MSWin32' and $ENV{'PWD'} =~ m|(/[^/]+(/[^/]+/[^/]+))(.*)|s) {
403 my($pd,$pi) = stat($2);
404 my($dd,$di) = stat($1);
405 if (defined $pd and defined $dd and $di == $pi and $dd == $pd) {
413 my $newdir = @_ ? shift : ''; # allow for no arg (chdir to HOME dir)
414 $newdir =~ s|///*|/|g unless $^O eq 'MSWin32';
415 chdir_init() unless $chdir_init;
417 if ($^O eq 'MSWin32') {
418 # get the full path name *before* the chdir()
419 $newpwd = Win32::GetFullPathName($newdir);
422 return 0 unless CORE::chdir $newdir;
425 return $ENV{'PWD'} = $ENV{'DEFAULT'}
427 elsif ($^O eq 'MacOS') {
428 return $ENV{'PWD'} = cwd();
430 elsif ($^O eq 'MSWin32') {
431 $ENV{'PWD'} = $newpwd;
435 if ($newdir =~ m#^/#s) {
436 $ENV{'PWD'} = $newdir;
438 my @curdir = split(m#/#,$ENV{'PWD'});
439 @curdir = ('') unless @curdir;
441 foreach $component (split(m#/#, $newdir)) {
442 next if $component eq '.';
443 pop(@curdir),next if $component eq '..';
444 push(@curdir,$component);
446 $ENV{'PWD'} = join('/',@curdir) || '/';
452 # In case the XS version doesn't load.
453 *abs_path = \&_perl_abs_path unless defined &abs_path;
454 sub _perl_abs_path(;$)
456 my $start = @_ ? shift : '.';
457 my($dotdots, $cwd, @pst, @cst, $dir, @tst);
459 unless (@cst = stat( $start ))
461 _carp("stat($start): $!");
466 # Make sure we can be invoked on plain files, not just directories.
467 # NOTE that this routine assumes that '/' is the only directory separator.
469 my ($dir, $file) = $start =~ m{^(.*)/(.+)$}
470 or return cwd() . '/' . $start;
472 # Can't use "-l _" here, because the previous stat was a stat(), not an lstat().
474 my $link_target = readlink($start);
475 die "Can't resolve link $start: $!" unless defined $link_target;
478 $link_target = $dir . '/' . $link_target
479 unless File::Spec->file_name_is_absolute($link_target);
481 return abs_path($link_target);
484 return abs_path($dir) . '/' . $file;
494 unless (opendir(PARENT, $dotdots))
496 _carp("opendir($dotdots): $!");
499 unless (@cst = stat($dotdots))
501 _carp("stat($dotdots): $!");
505 if ($pst[0] == $cst[0] && $pst[1] == $cst[1])
513 unless (defined ($dir = readdir(PARENT)))
515 _carp("readdir($dotdots): $!");
519 $tst[0] = $pst[0]+1 unless (@tst = lstat("$dotdots/$dir"))
521 while ($dir eq '.' || $dir eq '..' || $tst[0] != $pst[0] ||
524 $cwd = (defined $dir ? "$dir" : "" ) . "/$cwd" ;
526 } while (defined $dir);
527 chop($cwd) unless $cwd eq '/'; # drop the trailing /
532 # added function alias for those of us more
533 # used to the libc function. --tchrist 27-Jan-00
534 *realpath = \&abs_path;
540 my $path = @_ ? shift : ($Curdir ||= File::Spec->curdir);
542 # Detaint else we'll explode in taint mode. This is safe because
543 # we're not doing anything dangerous with it.
544 ($path) = $path =~ /(.*)/;
545 ($cwd) = $cwd =~ /(.*)/;
548 _croak("$path: No such file or directory");
552 # Make sure we can be invoked on plain files, not just directories.
554 my ($vol, $dir, $file) = File::Spec->splitpath($path);
555 return File::Spec->catfile($cwd, $path) unless length $dir;
558 my $link_target = readlink($path);
559 die "Can't resolve link $path: $!" unless defined $link_target;
561 $link_target = File::Spec->catpath($vol, $dir, $link_target)
562 unless File::Spec->file_name_is_absolute($link_target);
564 return fast_abs_path($link_target);
567 return fast_abs_path(File::Spec->catpath($vol, $dir, '')) . '/' . $file;
570 if (!CORE::chdir($path)) {
571 _croak("Cannot chdir to $path: $!");
573 my $realpath = getcwd();
574 if (! ((-d $cwd) && (CORE::chdir($cwd)))) {
575 _croak("Cannot chdir back to $cwd: $!");
580 # added function alias to follow principle of least surprise
581 # based on previous aliasing. --tchrist 27-Jan-00
582 *fast_realpath = \&fast_abs_path;
585 # --- PORTING SECTION ---
587 # VMS: $ENV{'DEFAULT'} points to default directory at all times
588 # 06-Mar-1996 Charles Bailey bailey@newman.upenn.edu
589 # Note: Use of Cwd::chdir() causes the logical name PWD to be defined
590 # in the process logical name table as the default device and directory
591 # seen by Perl. This may not be the same as the default device
592 # and directory seen by DCL after Perl exits, since the effects
593 # the CRTL chdir() function persist only until Perl exits.
596 return $ENV{'DEFAULT'};
600 return $ENV{'DEFAULT'} unless @_;
602 # may need to turn foo.dir into [.foo]
603 my $path = VMS::Filespec::pathify($_[0]);
604 $path = $_[0] unless defined $path;
606 return VMS::Filespec::rmsexpand($path);
610 $ENV{'PWD'} = `cmd /c cd`;
612 $ENV{'PWD'} =~ s:\\:/:g ;
617 $ENV{'PWD'} = Win32::GetCwd();
618 $ENV{'PWD'} =~ s:\\:/:g ;
622 *_NT_cwd = \&_win32_cwd if (!defined &_NT_cwd &&
623 defined &Win32::GetCwd);
625 *_NT_cwd = \&_os2_cwd unless defined &_NT_cwd;
628 if (!defined &Dos::GetCwd) {
629 $ENV{'PWD'} = `command /c cd`;
631 $ENV{'PWD'} =~ s:\\:/:g ;
633 $ENV{'PWD'} = Dos::GetCwd();
639 local $ENV{PATH} = '';
640 local $ENV{CDPATH} = '';
641 local $ENV{ENV} = '';
642 $ENV{'PWD'} = `/usr/bin/fullpath -t`;
648 local $ENV{PATH} = '';
649 local $ENV{CDPATH} = '';
650 local $ENV{ENV} = '';
651 my $path = @_ ? shift : '.';
654 open(REALPATH, '-|', '/usr/bin/fullpath', '-t', $path) or
655 die "Can't open /usr/bin/fullpath: $!";
656 my $realpath = <REALPATH>;
663 $ENV{'PWD'} = EPOC::getcwd();
668 # Now that all the base-level functions are set up, alias the
669 # user-level functions to the right places
671 if (exists $METHOD_MAP{$^O}) {
672 my $map = $METHOD_MAP{$^O};
673 foreach my $name (keys %$map) {
674 no warnings; # assignments trigger 'subroutine redefined' warning
676 *{$name} = \&{$map->{$name}};