Renaming files or directories using std::filesystem::path
involves the std::filesystem::rename()
function. This function allows you to move or rename files and directories efficiently. Here’s how you can do it:
Here’s an example of renaming a file:
#include <filesystem>
#include <iostream>
namespace fs = std::filesystem;
int main() {
fs::path oldPath{R"(C:\path\to\oldname.txt)"};
fs::path newPath{R"(C:\path\to\newname.txt)"};
try {
fs::rename(oldPath, newPath);
std::cout << "File renamed successfully";
} catch (const fs::filesystem_error& e) {
std::cerr << "Error: " << e.what();
}
}
File renamed successfully
Similarly, you can rename a directory:
#include <filesystem>
#include <iostream>
namespace fs = std::filesystem;
int main() {
fs::path oldDir{R"(C:\path\to\olddir)"};
fs::path newDir{R"(C:\path\to\newdir)"};
try {
fs::rename(oldDir, newDir);
std::cout << "Directory renamed successfully";
} catch (const fs::filesystem_error& e) {
std::cerr << "Error: " << e.what();
}
}
Directory renamed successfully
rename()
Function: Use std::filesystem::rename()
to rename files or directories.rename()
function may not work across different filesystems or devices. In such cases, use std::filesystem::copy()
and std::filesystem::remove()
.Proper error handling ensures your program can deal with scenarios where renaming fails:
#include <filesystem>
#include <iostream>
namespace fs = std::filesystem;
int main() {
fs::path oldPath{R"(C:\path\to\missing.txt)"};
fs::path newPath{R"(C:\path\to\new.txt)"};
try {
fs::rename(oldPath, newPath);
std::cout << "File renamed successfully";
} catch (const fs::filesystem_error& e) {
if (e.code() ==
std::errc::no_such_file_or_directory) {
std::cerr << "Error: File not found";
} else if (e.code() ==
std::errc::permission_denied) {
std::cerr << "Error: Permission denied";
} else {
std::cerr << "Error: " << e.what();
}
}
}
Error: File not found
Renaming files or directories with std::filesystem::path
is simple and efficient using std::filesystem::rename()
. Ensure you handle exceptions properly to create robust applications that manage file operations effectively.
Answers to questions are automatically generated and may not have been reviewed.
A guide to effectively working with file system paths, using the path
type within the standard library's filesystem
module.