Search code examples
c++winapidirectorycopyshfileoperation

Error using SHFileOperation() to copy a folder


I am trying to use SHFileOperation() to copy a folder, but get this error:

a value of type "const char *" cannot be assigned to an entity of type "PCZZWSTR"

for both s.pTo and s.pFrom.

The code I'm using is:

SHFILEOPSTRUCT s = { 0 };
s.hwnd = hWnd;
s.wFunc = FO_COPY;
s.fFlags = FOF_SILENT;
s.pTo = "C:\\Users\\styler\\Desktop\\Folder1\0";
s.pFrom = "C:\\Users\\styler\\Desktop\\Software\\Folder2\\Folder3\\*\0";
SHFileOperation(&s);

What am I doing wrong in s.pTo and s.pFrom? I am setting those equal to the target folder and the source folder, but why is this not working?


Solution

  • The compiler is telling you that you are trying to assign char string literals to wchar_t string pointers (PCZZWSTR = CONST WCHAR *). That means you must be compiling with UNICODE defined, where SHFileOperation() maps to SHFileOperationW() which expects wchar_t* string pointers instead of char* string pointers.

    So, you need to prefix your string literals with the L prefix, eg:

    SHFILEOPSTRUCT s = { 0 };
    s.hwnd = hWnd;
    s.wFunc = FO_COPY;
    s.fFlags = FOF_SILENT;
    s.pTo = L"C:\\Users\\styler\\Desktop\\Folder1\0";
    s.pFrom = L"C:\\Users\\styler\\Desktop\\Software\\Folder2\\Folder3\\*\0";
    SHFileOperation(&s);
    

    Or, since you are actually using the TCHAR version of SHFileOperation(), use the TEXT() macro to match your string literals to the actual character type used by TCHAR:

    SHFILEOPSTRUCT s = { 0 };
    s.hwnd = hWnd;
    s.wFunc = FO_COPY;
    s.fFlags = FOF_SILENT;
    s.pTo = TEXT("C:\\Users\\styler\\Desktop\\Folder1\0");
    s.pFrom = TEXT("C:\\Users\\styler\\Desktop\\Software\\Folder2\\Folder3\\*\0");
    SHFileOperation(&s);