Home > database >  Move directory and its contents to another directory
Move directory and its contents to another directory

Time:06-02

I'm trying to familiarize myself with C 17's filesystem library and I'm trying to implement the function

bool MoveFolder(std::string_view oldRelativePath, std::string_view newRelativePath)

which will take the folder at oldRelativePath and move it under newRelativePath. I've been fiddling around for an hour but no luck. How can I implement this function with std::filesystem? On any error, I would like to return false.

CodePudding user response:

You use std::filesystem::rename, of course.

Moves or renames the filesystem object identified by old_p to new_p as if by the POSIX rename.

CodePudding user response:

OK I found the problem with my earlier approach with std::filesystem::rename. Rename, as the name suggests, renames. It doesn't move. I was trying to use it like so:

fs::path p = fs::current_path() / "sandbox";
fs::create_directories(p / "from");
std::ofstream(p / "from/file1.txt").put('a');
fs::create_directory(p / "to");
fs::rename(p / "from", p / "to"); // NOT-OK
fs::remove_all(p);

This would lead to from being renamed to to, it wouldn't actually move from under to, which was what I wanted to do. Here's a simple way to achieve it:

fs::path p = fs::current_path() / "sandbox";
fs::create_directories(p / "from");
std::ofstream(p / "from/file1.txt").put('a');
fs::create_directory(p / "to");
fs::path ppp(p/"from");
fs::rename(p / "from", p / "to" / ppp.filename()); // OK
fs::remove_all(p);

And here is the function I've been desperately trying to implement...

bool MoveFolder(std::string_view oldRelativePath, std::string_view newRelativePath) {
   fs::path old(oldRelativePath);
   fs::path neww(newRelativePath);
   std::error_code err;
   fs::rename(old, old / neww.filename(), err);
   return !static_cast<bool>(err);
}
  • Related