CKTIS / C++
std::filesystem::rename: changing a name or location
std::filesystem::rename moves an entry from old_p to new_p with POSIX rename semantics and does not copy its contents.
Version: C++23
Syntax
void std::filesystem::rename(
const std::filesystem::path& old_p,
const std::filesystem::path& new_p);
void std::filesystem::rename(
const std::filesystem::path& old_p,
const std::filesystem::path& new_p, std::error_code& ec) noexcept;std::filesystem::rename(old_p, new_p) from <filesystem> changes a filesystem object’s name or location and returns void. If both paths resolve to the same existing file it does nothing; a symbolic link is moved as an entry rather than following its target.
The example creates old.txt, renames it to new.txt, checks both paths, and reads the content. Output 1 1 data confirms that the old name is absent, the new one exists, and the data is preserved.
An existing non-directory destination file can be replaced. Replacing an empty directory works on POSIX but can be an error on other systems; moving across filesystems can fail as well. The throwing form reports filesystem_error, while the error_code& form is noexcept and sets ec.
Examples
#include <filesystem>
#include <fstream>
#include <iostream>
#include <string>
int main() {
namespace fs = std::filesystem;
const fs::path root = fs::temp_directory_path() / "cktis-cpp-ref-rename";
const fs::path old_path = root / "old.txt";
const fs::path new_path = root / "new.txt";
std::error_code ignored;
fs::remove_all(root, ignored);
fs::create_directory(root);
std::ofstream(old_path) << "data";
fs::rename(old_path, new_path);
std::ifstream input(new_path);
std::string text;
input >> text;
input.close();
std::cout << !fs::exists(old_path) << ' ' << fs::exists(new_path) << ' ' << text << '\n';
fs::remove_all(root, ignored);
}
Result
1 1 data
std::filesystem::rename → 1 1 data