I am trying to use the std::rename()
function to move a .docx
file, however, the name of the file may vary. How can I use a std::string
within std::rename()
so that it does not have to be a hardcoded filepath, like this std::rename(filepath, destination);
?
Asked
Active
Viewed 50 times
0

Remy Lebeau
- 555,201
- 31
- 458
- 770
-
2[`std::string::c_str`](https://en.cppreference.com/w/cpp/string/basic_string/c_str)? – user4581301 Feb 04 '21 at 01:57
-
What is ```c_str```? – Feb 04 '21 at 01:58
-
2That's why it's a link. – WhozCraig Feb 04 '21 at 01:58
-
Use `std::string strSample; strSample.c_str();` – AleXelton Feb 04 '21 at 02:01
-
Bookmarking that duplicate link for my own dupe-closing. – user4581301 Feb 04 '21 at 02:07
-
2Consider using [`std::filesystem::rename()`](https://en.cppreference.com/w/cpp/filesystem/rename) instead of `std::rename()`, then you can pass `std::string` values without having to convert them to `char*` ([`std::filesystem::path`](https://en.cppreference.com/w/cpp/filesystem/path) can be constructed from `std::string`). – Remy Lebeau Feb 04 '21 at 02:22
1 Answers
1
I don't know how you want to populate the strings in question, but here you go:
std::string fromName {"whatever you're going to do"};
std::string toName {"whatever you're going to do"};
std::rename(fromName.c_str(), toName.c_str());

Joseph Larson
- 8,530
- 1
- 19
- 36