Renaming Files and Directories
How do I rename a file or directory using std::filesystem::path
?
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:
Renaming a File
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
Renaming a Directory
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
Key Points
- The
rename()
Function: Usestd::filesystem::rename()
to rename files or directories. - Exception Handling: Always use try-catch blocks to handle exceptions, as the function can throw errors if the operation fails.
- Cross-Device Renaming: The
rename()
function may not work across different filesystems or devices. In such cases, usestd::filesystem::copy()
andstd::filesystem::remove()
.
Error Handling
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
Conclusion
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.
File System Paths
A guide to effectively working with file system paths, using the std::filesystem::path
type.