Video Coming Soon...
35: cp
The cp command is very easy to create at first. There's a std::filesystem::copy_file API that mostly does it for you. The real difficulty comes when you implement the options to recursively copy or maintain permissions.
The Challenge
I'm giving you the starter code so you can learn a few tricks, and then push this example further. You'll see that I'm using namespace fs = std::filesystem to create an alias for std::filesystem. This helps cut down on the typing you have to do in C++. I'm also using it with fs::copy_file which is really std::filesystem::copy_file but using the fs alias we just made.
Your challenge is to implement a single option -r. The -r option recursively copies a directory. You already know how to list a directory--and recursively--from the previous exercise. You're now applying this technique to the problem of copying a directory.
The Code
Here's my starter code to get you going:
#include <fmt/core.h>
#include <filesystem>
#include <fstream>
#include <iostream>
namespace fs = std::filesystem;
int main(int argc, char* argv[]) {
if(argc != 3) {
fmt::println("USAGE: cp <from_file> <to_file>");
return 1;
}
try {
fs::copy_file(argv[1], argv[2]);
} catch(fs::filesystem_error &e) {
fmt::println("failed to copy: {}", e.what());
}
}
The Discussion
Being able to recursively process files is an important programming skill. If you write a tool that can do something to one file the next thing people want is doing it to all their files.
Whenever you work on these tools, see if it has any recursive option and try to implement it. This will usually require you to fix your code to handle many different situations you hadn't anticipated before. Doing something onces is usually easy. Do the same thing on a recursive structure is harder.
Further Study
The other option you can implement is -a to copy permissions, but this may be a problem on Windows. A better option to try is -u which does an update. That means it will only copy files that have changed, but the way it does this depends on a setting to -u.
You should also notice that I'm using exceptions to catch when the copy has a failure. Are there other places you could use this? Look at previous exercises and pick one to use exceptions to catch errors.
Register for Learn C++ the Hard Way
Register to gain access to additional videos which demonstrate each exercise. Videos are priced to cover the cost of hosting.