c++file-renamestd-filesystem

Renaming a file without changing its extension


I have a file name as a std::string that is comprised of a file and path, and I want to rename the file, but keep the extension the same.

As an example change abc to ijk:

/dir1/dir2/dir3/abc.txt  ---> /dir1/dir2/dir3/ijk.txt

../../dir1/abc.txt  ---> ../../dir1/ijk.txt

I know this can be done using some kind of string processing, but I'd like to use the std::filesystem path as it handles all the edge cases.

Is there a way to do this with the std::filesystem path facilities?


Solution

  • Had a similar situation when having to deal with path formats from different environments, writing a correct parsing or tokenizing process is not trivial, so ended up using the path class that comes with the std libraries.

    I think what you want shouldn't be called rename but rather change or modify,

    Here is some code that should get you what you're looking for:

    std::string change_filename(const std::string old_file_name, const std::string& new_file_name)
    {
        const std::filesystem::path& old_file {old_file_name};
        
        const std::string ext = old_file.has_extension() ? old_file.extension().string() : "";
        
        return (old_file.parent_path() / (new_file_name + ext)).string();
    };
    

    https://godbolt.org/z/Er3ejW83M