I'm trying to check if the path given exists. In case it doesn't, I'd like to create a folder with name given in the same directory.
Let's say pathOne: "/home/music/A" and pathTwo: "/home/music/B", such that folder A exists but folder B doesn't. 开发者_StackOverflow中文版Nothing happens if the path given by the user is pathOne, but if its pathTwo, then the program should realize that it doesn't exist in /home and should create it.
I know that it's possible to check the existence from files (with fopen it's possible do to that), but I don't know how to do that for folders!
Windows has pretty flaky support for POSIX, but this is one of those things it can do so my solution is good for Linux/Mac/POSIX/Windows):
bool directory_exists( const std::string &directory )
{
if( !directory.empty() )
{
if( access(directory.c_str(), 0) == 0 )
{
struct stat status;
stat( directory.c_str(), &status );
if( status.st_mode & S_IFDIR )
return true;
}
}
// if any condition fails
return false;
}
bool file_exists( const std::string &filename )
{
if( !filename.empty() )
{
if( access(filename.c_str(), 0) == 0 )
{
struct stat status;
stat( filename.c_str(), &status );
if( !(status.st_mode & S_IFDIR) )
return true;
}
}
// if any condition fails
return false;
}
Note that you can easily change the argument to a const char*
if you prefer that.
Also note that symlinks and such can be added in a platform specific way by checking for different values of status.st_mode
.
You should be able to use Boost Filesystem exists function. It's also portable.
There is a very good tutorial describing this very scenario, named Using status queries to determine file existence and type - (tut2.cpp)
You can use the opendir
function from 'dirent.h' and check for ENOENT
as return value.
This header file is not available on Windows. On Windows you use GetFileAttributes
and check for INVALID_FILE_ATTRIBUTES
as return value.
check out the boost filesystem library. It has a very convenient and high-level interface, e.g. exists(path)
, is_directory(path)
etc.
On the Linux OS level you can use stat.
精彩评论