CreateDirectory() and already existing directories

Can someone point me to the return values of CreateDirectory?

specifically I want to know if the directory already exists.
Who is Participating?
I wear a lot of hats...

"The solutions and answers provided on Experts Exchange have been extremely helpful to me over the last few years. I wear a lot of hats - Developer, Database Administrator, Help Desk, etc., so I know a lot of things but not a lot about one thing. Experts Exchange gives me answers from people who do know a lot about one thing, in a easy to use platform." -Todd S.

galneweinhawAuthor Commented:
Looks like it returns bool... not much help

how do I check if a dir already exists?
In general, it can be quite handy to do a google on "msdn AnyApiFunction".

In this case, the first hit is:


The CreateDirectory function creates a new directory. If the underlying file system supports security on files and directories, the function applies a specified security descriptor to the new directory.

To specify a template directory, use the CreateDirectoryEx function.

BOOL CreateDirectory(
  LPCTSTR lpPathName,
  LPSECURITY_ATTRIBUTES lpSecurityAttributes


    [in] Pointer to a null-terminated string that specifies the path of the directory to be created.

    There is a default string size limit for paths of 248 characters. This limit is related to how the CreateDirectory function parses paths.

    To extend this limit to 32,767 wide characters, call the Unicode version of the function and prepend "\\?\" to the path. For more information, see Naming a File.

        Windows Me/98/95:  This string must not exceed MAX_PATH characters.

    [in] Pointer to a SECURITY_ATTRIBUTES structure. The lpSecurityDescriptor member of the structure specifies a security descriptor for the new directory. If lpSecurityAttributes is NULL, the directory gets a default security descriptor. The ACLs in the default security descriptor for a directory are inherited from its parent directory.

    The target file system must support security on files and directories for this parameter to have an effect. (This is indicated when GetVolumeInformation returns FS_PERSISTENT_ACLS.)

Return Values

If the function succeeds, the return value is nonzero.

If the function fails, the return value is zero. To get extended error information, call GetLastError. Possible errors include the following.
Return code       Description
ERROR_ALREADY_EXISTS       The specified directory already exists.
ERROR_PATH_NOT_FOUND       One or more intermediate directories do not exist; this function will only create the final directory in the path. To create all intermediate directories on the path, use the SHCreateDirectoryEx function.

Some file systems, such as NTFS, support compression or encryption for individual files and directories. On volumes formatted for such a file system, a new directory inherits the compression and encryption attributes of its parent directory.

An application can obtain a handle to a directory by calling CreateFile with the FILE_FLAG_BACKUP_SEMANTICS flag set. For a code example, see CreateFile.

For backward compatibility purposes, CreateDirectory does not apply Windows 2000 inheritance rules when you specify a security descriptor in lpSecurityAttributes. To support inheritance on current versions of Windows, functions that query the security descriptor of this object may heuristically determine and report that inheritance is in effect. See Automatic Propagation of Inheritable ACEs for more information.
Example Code

For an example, see Retrieving and Changing File Attributes.

Client: Requires Windows XP, Windows 2000 Professional, Windows NT Workstation, Windows Me, Windows 98, or Windows 95.
Server: Requires Windows Server 2003, Windows 2000 Server, or Windows NT Server.
Unicode: Implemented as Unicode and ANSI versions. Note that Unicode support on Windows Me/98/95 requires Microsoft Layer for Unicode.
Header: Declared in Winbase.h; include Windows.h.
Library: Use Kernel32.lib.
See Also

CreateDirectoryEx, CreateFile, Directory Management Functions, RemoveDirectory, SECURITY_ATTRIBUTES, SECURITY_INFORMATION
If you want to check the existence of a directory, use

DWORD dwAtt = GetFileAttributes ("c:\\path\\dir");

if ( -1 != dwAtt && dwAtt & FILE_ATTRIBUTE_DIRECTORY){

    // exists and is a directory

If you want to use 'CreateDirectory()', evaluate 'GetLastError()' if 'CreateDirectory()' returns FALSE, e.g.

if ( !CreateDirectory("c:\\path\\dir")) {

    if ( ERROR_ALREADY_EXISTS == GetLastError()) {

        // directory exists already


Experts Exchange Solution brought to you by

Your issues matter to us.

Facing a tech roadblock? Get the help and guidance you need from experienced professionals who care. Ask your question anytime, anywhere, with no hassle.

Start your 7-day free trial
Cloud Class® Course: Microsoft Exchange Server

The MCTS: Microsoft Exchange Server 2010 certification validates your skills in supporting the maintenance and administration of the Exchange servers in an enterprise environment. Learn everything you need to know with this course.

I usually take the stat function to check directory status as it works on any platform

#include "sys/stat.h"

      struct stat fs;
      if (stat("c:\\mypath\\mydir", &fs) == 0)
           if ((fs.st_mode & S_IFDIR) != 0)
              cout << "directory already exists" << endl;
              cout << "file already exists" << endl;

Regards, Alex
"stat()" just tells you what was, not always a reliable indication of what is.

Actually trying the CreateDirectory() is the only sure way to know.

>>Actually trying the CreateDirectory() is the only sure way to know


DWORD dwAtt = GetFileAttributes ("c:\\path\\dir");

if ( -1 != dwAtt && dwAtt & FILE_ATTRIBUTE_DIRECTORY){

   // exists and is a directory
>>Actually trying the CreateDirectory() is the only sure way to know


DWORD dwAtt = GetFileAttributes ("c:\\path\\dir");

if ( -1 != dwAtt && dwAtt & FILE_ATTRIBUTE_DIRECTORY){

   // exists and is a directory


 I was getting at the fact that any file system inquiry only tells you what WAS, not what will be.

I got badly bitten by this years ago when I had one program creating backup directories, another program archiving them to tape.  Programs would work fine for about 97% of the time, but would randomly crash when things that were there one second were not there anymore a tad later.

I stand by my old statement:

Actually trying the CreateDirectory() is the only sure way to know

>>Actually trying the CreateDirectory() is the only sure way to know

to know what?

If you want to know, whether a directory exists or not and isn't a file but a directory, both GetFileAttributes and stat give reliable information. Also the non existence is a necessary precondition to creating the directory, so it makes sense to check that.

If you have to know, whether CreateDirectory would work for a given path because you always have to create a new directory, you don't need any other functions. Simply call it and check the error - if any.

But, if you need to create the directory only in rare cases, i would prefer to check existence rather then let it fail by calling CreateDirectory.

Regards, Alex

Maybe I'm not being clear enough.

if you do a "stat()" or a "GetFileAttributes()", that tells you the state of the file system at that instant.

Now 99% of the time you can get away with acting on that information.

But there's no way either API can guarantee what will be the state of things any time in the future, not even a nanosecond later.

For example, if you do a stat() or GetFileAttributes() and find that a directory is or is not there, you CANT in general go ahead and ASSUME the directory is or is not there, even a few statements later in the code.  For example if the directory isnt there, you can't assume a CreateDirectoryt() will succeed;  if the directory IS there, you can't assume it will be there by the time you try to do anything with it.

Sure, 99.4% of the time nothing will have  changed.   But if the system is running slow that day, or if a file defragmenter is running, or there's a surge of activity on the web server, or something else changes the system dynamics, KABOOM!

That's why it's unhealthy to even bother doing one of those inquiries, you'll be all too tempted to take the info as gospel.



It's more than this solution.Get answers and train to solve all your tech problems - anytime, anywhere.Try it for free Edge Out The Competitionfor your dream job with proven skills and certifications.Get started today Stand Outas the employee with proven skills.Start learning today for free Move Your Career Forwardwith certification training in the latest technologies.Start your trial today

From novice to tech pro — start learning today.

Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.