std::filesystem::path::replace_extension (3) - Linux Manuals

std::filesystem::path::replace_extension: std::filesystem::path::replace_extension


std::filesystem::path::replace_extension - std::filesystem::path::replace_extension


path& replace_extension( const path& replacement = path() ); (1) (since C++17)

Replaces the extension with replacement or removes it when the default value of replacement is used.
Firstly, if this path has an extension(), it is removed from the generic-format view of the pathname.
Then, a dot character is appended to the generic-format view of the pathname, if replacement is not empty or does not begin with a dot character.
Then replacement is appended as if by operator+=(replacement)


replacement - the extension to replace with

Return value





The type of replacement is std::filesystem::path even though it is not intended to represent an object on the file system in order to correctly account for the filesystem character encoding.


// Run this code

  #include <iostream>
  #include <filesystem>
  namespace fs = std::filesystem;

  int main()
      fs::path p = "/foo/bar.jpeg";
      std::cout << "Was: " << p << '\n';
      std::cout << "Now: " << p << '\n';


  Was: "/foo/bar.jpeg"
  Now: "/foo/bar.jpg"

See also

              returns the file extension path component
extension (public member function)
              returns the filename path component
filename (public member function)
              returns the stem path component
stem (public member function)
              checks if the corresponding path element is not empty
has_extension (public member function)