Search code examples
cwinapifile-copying

How to copy multiple files with CopyFile function?


Here is an example my code to copy file from src to dst:

int main() {

    const wchar_t* file[3] = { L"\\abc.txt", L"\\def.txt", L"\\ghi.txt" };

    for (int i = 0; i < 3; i++) {
        wchar_t* src = funcA();
        wchar_t* dst = funcB();
        wcscat(dst, file[i]);
        wcscat(src, file[i]);
        CopyFileW(src, dst, TRUE);
    }
}

Is there a better way to do that? Can I optimize the code by not running the funcA and funcB many times?


Solution

  • After you fix the errors, your code is copying the file to itself. It boils down to this:

    const wchar_t* file[3] = { L"\\abc.txt", L"\\def.txt", L"\\ghi.txt" };
    for(int i = 0; i < _countof(file); i++)
        CopyFile(file[i], file[i], TRUE);
    

    It's just copying "\\abc.txt" to "\\abc.txt", and "\\def.txt" to "\\def.txt", etc.

    Presumably your intention is to copy multiple files from one directory to another directory. For example copy "abc.txt" to "c:\\target\\abc.txt", etc.

    #include <stdio.h>
    #include <stdlib.h>
    #include <windows.h>
    
    int main(void)
    {
        const wchar_t* files[3] = { L"1.txt", L"2.txt", L"3.txt" };
    
        wchar_t *directory = L"c:\\target";
        wchar_t dst[MAX_PATH] = { 0 };
        for(int i = 0; i < _countof(files); i++)
        {
            swprintf(dst, _countof(dst), L"%ls\\%ls", directory, files[i]);
            CopyFileW(files[i], dst, TRUE);
        }
    
        return 0;
    }
    

    Note that I changed the source to "abc.txt" and changed the format specifier in swprintf

    In a practical application you may want to copy "c:\\src\\1.txt" to "c:\\dst\\1.txt", like this code:

    #define UNICODE
    #include <stdio.h>
    #include <stdlib.h>
    #include <windows.h>
    #include <Shlwapi.h>
    
    #pragma comment(lib, "Shlwapi.lib")//Add library (Visual Studio specific)
    
    int main(void)
    {
        const wchar_t* files[3] =
            { L"c:\\src\\1.txt", L"c:\\src\\2.txt", L"c:\\src\\3.txt" };
    
        wchar_t *directory = L"c:\\dst";
        wchar_t dst[MAX_PATH] = { 0 };
    
        if(!PathFileExists(directory))
        {
            wprintf(L"path error\n");
            return 0;
        }
    
        for(int i = 0; i < _countof(files); i++)
        {
            swprintf(dst, _countof(dst), L"%ls\\%ls", directory, PathFindFileName(files[i]));
            //CopyFile(files[i], dst, TRUE);
            wprintf(L"copy %s to %s\n", files[i], dst);
        }
    
        return 0;
    }