C++: How to check if a file/directory is readable? (PHP equivalent: is_readable)
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.boo开发者_开发技巧st.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?
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"); }
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, useboost::filesystem::directory_iterator
, if it succeeds, directory is readable.
Most operating systems provide stat().
精彩评论