How do I recursively create a folder in Win32?

前端 未结 14 1321
孤城傲影
孤城傲影 2020-12-01 14:11

I\'m trying to create a function that takes the name of a directory (C:\\foo\\bar, or ..\\foo\\bar\\..\\baz, or \\\\someserver\\foo\\bar

14条回答
  •  佛祖请我去吃肉
    2020-12-01 14:15

    Here is a function I wrote which iteratively creates a folder tree. Here is the main function:

    #include 
    #include 
    #include 
    #include 
    
    // Returns false on success, true on error
    bool createFolder(std::string folderName) {
        list folderLevels;
        char* c_str = (char*)folderName.c_str();
    
        // Point to end of the string
        char* strPtr = &c_str[strlen(c_str) - 1];
    
        // Create a list of the folders which do not currently exist
        do {
            if (folderExists(c_str)) {
                break;
            }
            // Break off the last folder name, store in folderLevels list
            do {
                strPtr--;
            } while ((*strPtr != '\\') && (*strPtr != '/') && (strPtr >= c_str));
            folderLevels.push_front(string(strPtr + 1));
            strPtr[1] = 0;
        } while (strPtr >= c_str);
    
        if (_chdir(c_str)) {
            return true;
        }
    
        // Create the folders iteratively
        for (list::iterator it = folderLevels.begin(); it != folderLevels.end(); it++) {
            if (CreateDirectory(it->c_str(), NULL) == 0) {
                return true;
            }
            _chdir(it->c_str());
        }
    
        return false;
    }
    

    The folderExists routine is as follows:

    // Return true if the folder exists, false otherwise
    bool folderExists(const char* folderName) {
        if (_access(folderName, 0) == -1) {
            //File not found
            return false;
        }
    
        DWORD attr = GetFileAttributes((LPCSTR)folderName);
        if (!(attr & FILE_ATTRIBUTE_DIRECTORY)) {
            // File is not a directory
            return false;
        }
    
        return true;
    }
    

    An example call I tested the above functions with is as follows (and it works):

    createFolder("C:\\a\\b\\c\\d\\e\\f\\g\\h\\i\\j\\k\\l\\m\\n\\o\\p\\q\\r\\s\\t\\u\\v\\w\\x\\y\\z");
    

    This function hasn't gone through very thorough testing, and I'm not sure it yet works with other operating systems (but probably is compatible with a few modifications). I am currently using Visual Studio 2010 with Windows 7.

提交回复
热议问题