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?

augustin
  • 14,373
  • 13
  • 66
  • 79

2 Answers2

4

Most operating systems provide stat().

Tony Delroy
  • 102,968
  • 15
  • 177
  • 252
4
  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
  • 82,554
  • 44
  • 203
  • 280
  • 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 Aug 25 '10 at 06:36
  • 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. Aug 25 '10 at 08:38
  • @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 Aug 25 '10 at 10:43
  • Yes, in this case, I don't actually want to read anything, but check that the directory is readable before saving a setting. – augustin Aug 25 '10 at 13:15