C/C++ Copy file with automatic recursive folder/directory creation

前端 未结 2 1328
野性不改
野性不改 2020-12-17 03:15

In Win32 API, there is CopyFile that literally copies a file. However, this API doesn\'t create folders. For example, I\'d like to copy C:\\Data\\output.txt to

2条回答
  •  萌比男神i
    2020-12-17 04:12

    You can achieve desired result using SHCreateDirectoryEx. Here is an example:

    inline void EnsureDirExists(const std::wstring& fullDirPath)
    {
        HWND hwnd = NULL;
        const SECURITY_ATTRIBUTES *psa = NULL;
        int retval = SHCreateDirectoryEx(hwnd, fullDirPath.c_str(), psa);
        if (retval == ERROR_SUCCESS || retval == ERROR_FILE_EXISTS || retval == ERROR_ALREADY_EXISTS)
        return; //success
    
        throw boost::str(boost::wformat(L"Error accessing directory path: %1%; win32 error code: %2%") 
           % fullDirPath
           % boost::lexical_cast(retval));
    
        //TODO *djg* must do error handling here, this can fail for permissions and that sort of thing
    }
    

提交回复
热议问题