Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

File renaming in C++ [duplicate]

Tags:

c++

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!

like image 455
Sba Avatar asked Mar 23 '26 20:03

Sba


2 Answers

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;
    }
}
like image 161
mediocrevegetable1 Avatar answered Mar 26 '26 09:03

mediocrevegetable1


If you're using C++17 or later, you can try std::filesystem::rename.

like image 36
ruipacheco Avatar answered Mar 26 '26 09:03

ruipacheco



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!