0

I am working With files. Currently I am sequentially renaming some files I know a little about fstream. I simply want to rename multiple file sequentially with loop.Why this code is not working? Is there any another way to do? i just want to done my job. Thank you for reading <3

#include <iostream>
#include <cstdio>

using namespace std;

int main()
{

// not working
for(int i=1;i<=20;i++;){
 
 rename(("oldname"+to_string(i)+"txt"),((newname+to_string(i)+"txt"));



}
    
return 0;
}
  • 2
    *Why this code is not working?* -- What do you mean by "not working"? What error(s) are you receiving? – PaulMcKenzie Sep 16 '20 at 06:36
  • Does this answer your question? [How to concatenate two strings in C++?](https://stackoverflow.com/questions/15319859/how-to-concatenate-two-strings-in-c) – David C. Rankin Sep 16 '20 at 07:06

1 Answers1

2

std::rename takes two parameters of type const char *. But the result of string concatenation is std::string. You can use .c_str() to access to underlying C-style-string like so:

auto oldFileName = "oldname" + to_string(i) + "txt";
auto newFileName = newname + to_string(i) + "txt";

rename(oldFileName.c_str(), newFileName.c_str());

But it can get easier than this: rename is a relic from C. In C++ you should use std::filesystem::rename (if you can use C++17). One advantage is, that in can work with std::string.

Lukas-T
  • 11,133
  • 3
  • 20
  • 30