How do I recursively create a folder in Win32?

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

    Good example:

    BOOL DirectoryExists(LPCTSTR szPath)
    {
      DWORD dwAttrib = GetFileAttributes(szPath);
    
      return (dwAttrib != INVALID_FILE_ATTRIBUTES &&
        (dwAttrib & FILE_ATTRIBUTE_DIRECTORY));
    }
    
    void createDirectoryRecursively(std::wstring path)
    {
      signed int pos = 0;
      do
      {
        pos = path.find_first_of(L"\\/", pos + 1);
        CreateDirectory(path.substr(0, pos).c_str(), NULL);
      } while (pos != std::wstring::npos);
    }
    
    //in application
    int main()
    {
      std::wstring directory = L"../temp/dir";
      if (DirectoryExists(directory.c_str()) == FALSE)
        createDirectoryRecursively(directory);
      return 0;
    }
    
    0 讨论(0)
  • 2020-12-01 14:34

    Note: this answer is somewhat quick and dirty, and doesn't handle all cases. If this is ok with you, read on. If not, consider using one of the other options.


    You can use good old mkdir for that. Just run

    system("mkdir " + strPath);
    

    and you're done.

    Well, almost. There are still cases you have to take care of, such as network shares (which might not work) and backslashes. But when using relatively safe paths, you can use this shorter form.

    Another thing you might find useful getting rid of the possible nuisance is _fullpath(), which will resolve the given path into a full and clean one. Knowing you have a clean path, you should have no problem writing a rather trivial recursive function that will create the folders one by one, even when dealing with UNC paths.

    0 讨论(0)
提交回复
热议问题