Beefy Boxes and Bandwidth Generously Provided by pair Networks
Come for the quick hacks, stay for the epiphanies.
 
PerlMonks  

Checking for directory write permissions

by sara2005 (Scribe)
on Jun 26, 2006 at 18:03 UTC ( [id://557627] : perlquestion . print w/replies, xml ) Need Help??

sara2005 has asked for the wisdom of the Perl Monks concerning the following question:

Hi Monks

I have to write files in certain directories and I need to return an error, if there is no write access.

I am not able to use opendir and readdir functions as they work perfectly if there is read access.

Is there a way to check the directory permissions?

  • Comment on Checking for directory write permissions

Replies are listed 'Best First'.
Re: Checking for directory write permissions
by ikegami (Patriarch) on Jun 26, 2006 at 18:06 UTC

    You can use -w on directories.

    But do you really need to check that? Just check whether open fails or not by examing $!:

    $ perl -le 'open(FILE, ">", "nowrite/newfile") > or die("Unable to create file: $!\n")' Unable to create file: Permission denied

    Update: I originally checked if the dir was readable. Fixed.

Re: Checking for directory write permissions
by shmem (Chancellor) on Jun 26, 2006 at 18:21 UTC
    Just use
    if( not -w $dir) { die "directory $dir not writeable.\n"; }
    The test -w works for files and directories. See perlfunc, -X (file tests).
    _($_=" "x(1<<5)."?\n".q·/)Oo.  G°\        /
                                  /\_¯/(q    /
    ----------------------------  \__(m.====·.(_("always off the crowd"))."·
    ");sub _{s./.($e="'Itrs `mnsgdq Gdbj O`qkdq")=~y/"-y/#-z/;$e.e && print}

      Thanks a lot

      -w option worked!!

        Warning. The -w option will give you a misleading postive result in the case where you have permissions, but the partition is mounted read-only (popular for NFS on unix). We actually just wrote a quick function to test writeability by opening a file for write access wherever we were checking, and, if successful, deleting it afterwards. It was the only foolproof way we could come up with of detecting the situation.

Re: Checking for directory write permissions
by Fletch (Bishop) on Jun 26, 2006 at 18:15 UTC

    As an alternate to using -w or stat, just try and write and handle the error. If the open returns failure check if $! == EACCESS; if it does then there was a permissions problem (presuming you've done a use POSIX qw( :errno_h ) of course).

      I think this is a better solution, or at least one that should not be overlooked. Actually trying to write the file can also expose other errors (disk full comes to mind, etc.) which may not be identified by a simple -w (especially at the directory level).


      No good deed goes unpunished. -- (attributed to) Oscar Wilde