简体   繁体   中英

Create directory on Windows and check if it exists

I have to create some directories and when I try to search one I have to know if it was already created.

The problem is that after creating a directory with CreateDirectory() and trying to check if it was created I get an error which says that it wasn't created.

If I close and restart the program, without creating the directory but just checking if it was created, everything works.

bool DirectoryExists( const char* absolutePath ){
    if( _access( absolutePath, 0 ) == 0 ){
        struct stat status;
        stat( absolutePath, &status );
        return (status.st_mode & S_IFDIR) != 0;
    }
    return false;
}

marca = "database\\"+marca;
CreateDirectory (marca.c_str(), NULL);
// useless operation
if(! DirectoryExists(marca.c_str() )  )
{
    cout<<" Error !";
    return -1;
}

If marca was "database" it would work. But if marca is "database/foo" you cannot create both of these at the same time.

Here's a version of your code where I separate these operations.

#include <windows.h>
#include <io.h>
#include <string>
#include <cstdio>
#include <cstdlib>
#include <iostream>

using namespace std;

bool DirectoryExists( const char* absolutePath )
{
    if( _access( absolutePath, 0 ) == 0 ){

        struct stat status;
        stat( absolutePath, &status );

        return (status.st_mode & S_IFDIR) != 0;
    }
    return false;
}

bool MakeDirectory(const string& marca)
{
    if(! CreateDirectory(marca.c_str(), NULL))
    {
        DWORD error = GetLastError();
        TCHAR buf[256];
        FormatMessage(FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_IGNORE_INSERTS,
            NULL, GetLastError(), MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT), 
            buf, (sizeof(buf) / sizeof(TCHAR)), NULL);
        cout << "Failed to create directory: " << buf << '\n';
        return false;
    }

    if(! DirectoryExists(marca.c_str() )  )
    {
        cout << "Directory does not exist\n";
        return false;
    }
    return true;
}

int main()
{
    // name of subdirectory
    string marca = "foo"; 

    // first create top directory
    string d = "database";
    MakeDirectory(d);

    // then subdirectory
    d += "/" + marca;
    MakeDirectory(d);

    return 0;

}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM