Search code examples
c++filerenamefile-renamecstdio

How do I use std::rename with variables?


In my program, I store data in different text files. The data belongs to an object, which I call rockets. For example, the rocket Saturn 5 has a text file labeled "Saturn5R.txt". I want an option to rename the rocket, and so I will need to rename the text file as well. I am using std::rename in the library. I have gotten it working with something like this:

char oldname[] = "Saturn5R.txt";
char newname[] = "Saturn6R.txt";

if (std::rename(oldname, newname) != 0) {
    perror("Error renaming file");
}

This works, but I don't want to always be renaming Saturn5R.txt to Saturn6R.txt. What I want to do is to be able to rename any text file to any name, I have tried this and I get an error:

char oldname[] = rocketName + RocketNumber + "R.txt";
char newname[] = NameChoice + NumberChoice + "R.txt";
if (std::rename(oldname, newname) != 0) {
    perror("Error renaming file");      
}

This returns the error "[cquery] array initializer must be an initializer list or string literal". How can I use std::rename or any other file renaming function that allows me to rename any files I want without hardcoding them in?


Solution

  • This has little to do with std::rename, and everything to do with how to interpolate variables into a string. A simple solution is to use std::string. It has overloaded operator + that can be used to concatenate substrings.

    If you want to make the program a bit fancier, C++20 added std::format:

    std::string oldname = std::format("{}{}R.txt", rocketName, RocketNumber);
    std::string newname = std::format("{}{}R.txt", NameChoice, NumberChoice);
    if (std::rename(oldname.c_str(), newname.c_str()) != 0) {
    

    P.S. I recommend using std::filesystem::rename instead since it has better ways of handling errors in my opinion.