[Last Call] Learn how to a build a cloud-first strategyRegister Now

x
  • Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 2233
  • Last Modified:

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.
0
galneweinhaw
Asked:
galneweinhaw
  • 4
  • 2
  • 2
  • +1
1 Solution
 
galneweinhawAuthor Commented:
Looks like it returns bool... not much help

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

In this case, the first hit is:

CreateDirectory

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
);

Parameters

lpPathName
    [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.

lpSecurityAttributes
    [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.
Remarks

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

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
 
0
 
jkrCommented:
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
    }

}
0
VIDEO: THE CONCERTO CLOUD FOR HEALTHCARE

Modern healthcare requires a modern cloud. View this brief video to understand how the Concerto Cloud for Healthcare can help your organization.

 
itsmeandnobodyelseCommented:
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;
           else
              cout << "file already exists" << endl;
      }

Regards, Alex
           
0
 
grg99Commented:
"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.

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

No:

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

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

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

No:

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


0
 
itsmeandnobodyelseCommented:
>>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



0
 
grg99Commented:
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.

Regards,

 

0

Featured Post

VIDEO: THE CONCERTO CLOUD FOR HEALTHCARE

Modern healthcare requires a modern cloud. View this brief video to understand how the Concerto Cloud for Healthcare can help your organization.

  • 4
  • 2
  • 2
  • +1
Tackle projects and never again get stuck behind a technical roadblock.
Join Now