Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to rename a file using wstring?

Tags:

c++

visual-c++

How can I rename a file in c++?

rename(tempFileName.c_str(), tempFileName.c_str()+"new.txt");

But tempFileName is of type std::wstring. But rename() functions accepts only const char* parameters.

like image 621
mystack Avatar asked Mar 22 '13 11:03

mystack


2 Answers

In Visual C++, the wide-character version of rename() is _wrename(). This isn't portable, but you may not care about that. Also, you can't add raw string pointers like that, you want something like this (not tested):

std::wstring newName(tempFileName);
newName += L"new.txt";
_wrename(tempFileName.c_str(), newName.c_str());
like image 170
DavidK Avatar answered Sep 28 '22 16:09

DavidK


When working with Visual Studio, you usually work with wide-strings. In order to rename the file you can use MoveFileEx-function, you can rename the file like this.

std::wstring newFilename = tempFileName.c_str();
newFilename += _T("new.txt");
if(!MoveFileEx(tempFileName.c_str(), newFilename.c_str(), flags )){
//error handling if call fails
}

See here for the documentation.

like image 32
bash.d Avatar answered Sep 28 '22 14:09

bash.d