I'm translating a piece of code I wrote in Java a long time ago to C++ because I want a .exe I can use directly form windows terminal without the need to install Java.
I need to be able to rename a set of files inside a directory of choice (that's what the code does) and I'm having trouble finding the best approach to follow with C++.
Can anyone give me a hint? Thanks!
If you have C++17 or above you can use std::filesystem::rename:
#include <iostream>
#include <filesystem>
int main()
{
namespace stdfs = std::filesystem;
stdfs::path p = stdfs::current_path();
stdfs::rename(p/"foo.txt", p/"new.txt");
}
If not, you could use the C function std::rename:
#include <iostream>
#include <cstdio>
int main()
{
if (std::rename("new.txt", "foo.txt") != 0)
{
std::perror("std::rename");
return 1;
}
}
If you're using C++17 or later, you can try std::filesystem::rename.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With