views:

66

answers:

2

I am trying to validate a directory with C++.

http://php.net/manual/en/function.is-readable.php

bool is_readable ( string $filename )
Tells whether a file (or directroy) exists and is readable.

What would be the equivalent of the above in C++?

I am already using the boost/filesystem library to check that the directory exists. I have checked the documentation:
http://www.boost.org/doc/libs/1_44_0/libs/filesystem/v3/doc/index.htm
but I cannot find the equivalent of PHP's is_readable().

If it is not possible with the boost/filesystem library, what method would you use?

+2  A: 

Most operating systems provide stat().

Tony
+3  A: 
  1. Since you've tagged the question "Linux", there is a POSIX function to check if the file is readable/writable/executable by the user of the current process. See man 2 access.

    int access(const char *pathname, int mode);
    

    For example,

    if (-1 == access("/file", R_OK))
    {
        perror("/file is not readable");
    }
    
  2. Alternatively, if you need portability, try to actually open the file for reading (e.g. std::ifstream). If it succeeds, the file is readable. Likewise, for directories, use boost::filesystem::directory_iterator, if it succeeds, directory is readable.

Alex B
Thanks. A quick follow up question: I don't have the relevant man pages installed ("No manual entry for access in section 2"). Would you know the package name to install on Debian/Kubuntu?
augustin
@augustin, IIRC in {U,Ku}buntu it's `manpages-dev`.
Alex B
@AlexB, Bingo! You are right. Thanks again.
augustin
imho the correct way is no. 2 anyway, you have no guarantee if access returns success that it is still readable when you rty to read from it
jk
@jk yes, there is always a TOCTOU race condition possible if you try to open it later, but it works for one-off reporting purposes (i.e. when only a check is needed).
Alex B
Yes, in this case, I don't actually want to read anything, but check that the directory is readable before saving a setting.
augustin