DEV Community

Gurkirat Singh
Gurkirat Singh

Posted on

Windows System Programming: Copying Files / Directory

Howdy readers, hope you are doing good. So previously you have learn about what system programming is and how to create a directory.

Now in this post, you will learn about copying files or folders from one path to another.

So for copying files whose names are in ANSI string, you should use CopyFileA. You can find the declaration of this function in WinBase.h

The function definition would look like this

BOOL CopyFileA(
  LPCSTR lpExistingFileName,
  LPCSTR lpNewFileName,
  BOOL   bFailIfExists
);
Enter fullscreen mode Exit fullscreen mode

Function parameters description as follows

  • lpExistingFileName → Pass the path of the existing file / folder (aka source path). If the path doesn't exist, you will get ERROR_FILE_NOT_FOUND
  • lpNewFileName %rarr; Pass the path of the new file (the location where you want to copy the file and the name of the file, aka destination path)
  • bFailIfExists → If this is TRUE and file lpNewFileName already exists, it will return ERROR_ALREADY_EXISTS. Otherwise, it will overwrite the new file.

So suppose, if you want to copy a file from C:\secret.txt to D:\secret-file.txt and it the file already exists, then it should be overwritten, the function should be called like below

CopyFileA(
  "C:\\secret.txt",
  "D:\\secret-file.txt",
  FALSE
);
Enter fullscreen mode Exit fullscreen mode

The complete code as follows

#include <Windows.h>
#include <iostream>
#include <WinBase.h>

int main(int argc, char** argv)
{

    if (argc == 1) {
        printf("usage: %s <old filename> <new filename>\n", argv[0]);
        return 1;
    }

    /*
     * For function documentation
     * https://docs.microsoft.com/en-us/windows/win32/api/winbase/nf-winbase-copyfilea
     */
    BOOL flag = CopyFileA(argv[1], argv[2], TRUE);

    if (flag) {
        printf("File Copied\n");
    }
    else {
        switch (GetLastError())
        {
        case ERROR_FILE_NOT_FOUND:
            printf("ERR: File '%s' not found\n", argv[1]);
            break;
        case ERROR_FILE_EXISTS:
            printf("ERR: File '%s' already exists\n", argv[2]);
            break;
        default:
            printf("ERR: %d\n", GetLastError());
            break;
        }
        return 1;
    }
    return 0;
}
Enter fullscreen mode Exit fullscreen mode

Hope you have learnt something new today. Follow the links to reach me

Top comments (0)