MFC: Create Directory

Original link: How to check if Directory already Exists in MFC(VC++)?

 

MSDN Links:

CreateDirectory function

GetFileAttributes function

GetLastError function

System Error Codes

 

Example:

VC++  MFC DLL project

#include "stdafx.h"
#include <windows.h>
#include <Shellapi.h>

    // To check if a file/folder exists:

    // Method 1: GetFileAttributes
    // Description: 
    // Retrieves file system attributes for a specified file or directory.
    // Return value:
    //   a) If the function succeeds, the return value contains the attributes of the specified file or directory. For a list of attribute values and their descriptions, see File Attribute Constants.
    //   b) If the function fails, the return value is INVALID_FILE_ATTRIBUTES. To get extended error information, call GetLastError.
    if (GetFileAttributes(szDirPath) == INVALID_FILE_ATTRIBUTES) {
        CreateDirectory(szDirPath,NULL);
    }

    // Method 2: CreateDirectory
    // Description:
    // Creates a new directory
    // Return value:
    //   a) If the function succeeds, the return value is nonzero.
    //   b) If the function fails, the return value is zero. To get extended error information, call GetLastError. 
    if(!CreateDirectory(szDirPath,NULL))
    { 
        if (GetLastError() == ERROR_ALREADY_EXISTS) {
            // directory already exists
        } else {
            // creation failed due to some other reasons
        }
    }

 

posted @ 2014-05-29 09:45  細水長流  阅读(986)  评论(0编辑  收藏  举报