Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use C++ to Copy A Directory [duplicate]

I have made a backup program using c++, but it uses the System() command to batch copy files.

I am looking for a way to copy an entire directory (this does not need to create any directories, just copy them). Or alternatively, copy everything within a directory.

For example, I want to copy C:\Users\ to E:\Backup\ Or C:\Users\* to E:\Backup\.

If possible could you include an example in your answer.

Thanks a lot!

like image 642
Liam Pufferfish Daly Avatar asked Jan 17 '13 11:01

Liam Pufferfish Daly


People also ask

How do I duplicate a folder?

Alternatively, right-click the folder, select Show more options and then Copy. In Windows 10 and earlier versions, right-click the folder and select Copy, or click Edit and then Copy. Navigate to the location where you want to place the folder and all its contents.

Can cp command copy directories?

With cp command, you can copy a directory and an entire subdirectory with its content and everything beneath it. cp and rsync are one of the most popular commands for copying files and directory.

What is the command to copy a directory?

Copy a Directory and Its Contents ( cp -r ) Similarly, you can copy an entire directory to another directory using cp -r followed by the directory name that you want to copy and the name of the directory to where you want to copy the directory (e.g. cp -r directory-name-1 directory-name-2 ).


3 Answers

As of today, C++17's <filesystem> is the proper solution.

#include <filesystem>

int main()
{
    std::filesystem::copy("C:/Users/", "E:/Backup/");
}

The slashes (/) are interpreted as directory separators, this is easier to read than a double back-slash (\\).

like image 122
YSC Avatar answered Sep 28 '22 12:09

YSC


The approach using System will not be platform independent. I strongly recommend using boost::filesystem for such tasks.

like image 20
Ivaylo Strandjev Avatar answered Sep 28 '22 13:09

Ivaylo Strandjev


1) include .h files:

#include <csystem>

2) write cmd:

system("copy c:\users\ e:\Backup\");

Tips: You can write everything in " " , just like you copy directorys in cmd.

like image 23
KingsOfTechENG Avatar answered Sep 28 '22 13:09

KingsOfTechENG