How do I recursively create a folder in Win32?

前端 未结 14 1313
孤城傲影
孤城傲影 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:18

    Here's a version that works with no external libraries, so Win32-only, and that function in all versions of Windows (including Windows CE, where I needed it):

    wchar_t *path = GetYourPathFromWherever();
    
    wchar_t folder[MAX_PATH];
    wchar_t *end;
    ZeroMemory(folder, MAX_PATH * sizeof(wchar_t));
    
    end = wcschr(path, L'\\');
    
    while(end != NULL)
    {
        wcsncpy(folder, path, end - path + 1);
        if(!CreateDirectory(folder, NULL))
        {
            DWORD err = GetLastError();
    
            if(err != ERROR_ALREADY_EXISTS)
            {
                // do whatever handling you'd like
            }
        }
        end = wcschr(++end, L'\\');
    }
    

提交回复
热议问题