rename() returns -1. How to know why rename fails?

Imran Shafqat picture Imran Shafqat · Sep 6, 2012 · Viewed 12.2k times · Source

I am using c++ stdio.h's

int rename ( const char * oldname, const char * newname );

rename() function to rename a folder but occasionally it fails to rename the folder and returns -1.

Is there any way to know why is rename() failing?
any way to know this error explanation via any c++ function.

Answer

Alex picture Alex · Sep 6, 2012

It should be possible to get the concrete error from errno.h

#include <errno.h>
#include <string.h>
...
if(rename("old","new") == -1)
{
    std::cout << "Error: " << strerror(errno) << std::endl;
}

The errno error codes for rename are OS-specific: