Modify a text file's name

How can I add some words when opening a new text file with the name based on the old text file?

For instance:

My input file is "player.txt"

and I want my output file to have the same name but adding some words like " playersss.txt"
<cstdio>'s rename function would be the simplest function to call. (<filesystem> I'm sure could do it as well)

https://www.programiz.com/cpp-programming/library-function/cstdio/rename
Last edited on
This is what std::filesystem is for, but you could just use standard string manipulation too:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
#include <string>

std::string add_filename_suffix_v1( const std::string& filename, const std::string& suffix )
{
  auto n = filename.rfind( '.' );
  if (filename.find_first_of( "/\\", n ) != filename.npos) return filename + suffix;
  return filename.substr( 0, n ) + suffix + filename.substr( n );
}


#include <filesystem>
#include <string>

std::string add_filename_suffix_v2( const std::string& filename, const std::string& suffix )
{
  std::filesystem::path p{ filename };
  return p.replace_filename( p.stem().string() + suffix + p.extension().string() ).string();
}


#include <iostream>

int main()
{
  std::cout << add_filename_suffix_v1( "C:/Users/heomap1/foo.stuff/player.txt", "001" ) << "\n";
  std::cout << add_filename_suffix_v2( "C:/Users/heomap1/foo.stuff/player.txt", "002" ) << "\n";
}

Hope this helps.
Topic archived. No new replies allowed.