mystack
mystack

Reputation: 5492

How to rename a file using wstring?

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.

Upvotes: 5

Views: 5286

Answers (3)

bash.d
bash.d

Reputation: 13207

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.

Upvotes: 5

user31394
user31394

Reputation:

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());

Upvotes: 9

wilx
wilx

Reputation: 18228

Since you are targeting Windows, use the _wrename() function instead.

Upvotes: 2

Related Questions