1

I want to create a folder named sessionname. If a folder with this name already exists it is fine, and I don't want to do anything.

Right now I do this:

finalpath = "/home/Documents"    
finalpath.append(path + "/" + sessionname);
    if (mkdir(finalpath.c_str(), S_IRWXU | S_IRWXG | S_IROTH | S_IXOTH) == -1)
    {
        //INVALID PATH
        std::cout << "path is invalid, cannot create sessionnamefolder" << std::endl;
        throw std::exception();
    }

This code errors, if the folder /home/Documents/sessionname exists because the folder couldn't be created.

How can I check if mkdir fails because the string was invalid or because the string was vaild but the folder already exists ?

Bryan
  • 17,112
  • 7
  • 57
  • 80
Peter111
  • 803
  • 3
  • 11
  • 21

2 Answers2

5

How can I check if mkdir fails because the string was invalid or because the string was vaild but the folder already existed?

Return code from mkdir() shows if function is successful or not. In case of failure you should check special variable errno, details can be found on man page

if (mkdir(finalpath.c_str(), S_IRWXU | S_IRWXG | S_IROTH | S_IXOTH) == -1)
{
    if( errno == EEXIST ) {
       // alredy exists
    } else {
       // something else
        std::cout << "cannot create sessionnamefolder error:" << strerror(errno) << std::endl;
        throw std::runtime_error( strerror(errno) );
    }
}

Note: this is common method for Linux/Unix (and other POSIX systems) library functions to report details of error condition.

Slava
  • 43,454
  • 1
  • 47
  • 90
1

As commented, it's mentioned on the mkdir - make a directory - manual page, one of the errors mkdir can get you is if [EEXIST] -> The named file exists. So it fails. See here for the mkdir main page. And here is a possible duplicate on stackoverflow.

Community
  • 1
  • 1
Khalil Khalaf
  • 9,259
  • 11
  • 62
  • 104