Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Check folder path

Tags:

c++

directory

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. 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!

like image 896
Kunal Vyas Avatar asked Dec 09 '25 09:12

Kunal Vyas


1 Answers

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.

like image 130
rubenvb Avatar answered Dec 11 '25 23:12

rubenvb



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!