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

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:

  • Linux error codes
  • Windows error codes (use _errno instead of errno)

C API functions like this typically set errno when they fail to give more information. The documentation will usually tell you about errno values it might set, and there's also a function called strerror() which will take an errno value and give you back a char * with a human-readable error message in it.

You may need to include <errno.h> to access that.

With regard to rename() in MFC, this would seem to be the documentation for it: http://msdn.microsoft.com/en-us/library/zw5t957f(v=vs.100).aspx which says it sets errno to EACCES, ENOENT or EINVAL under various conditions, so check against those to figure out what's going on, with reference to the documentation for the specifics.


Edit: Since the other questions of the asker if from Windows background I put the focus on the Windows programming environment. Other OS may differ. e.g. GCC/Linux provides errno instead of _errno

Check the value of _errno. It can be one of these:

EACCES: File or directory specified by newname already exists or could not be created (invalid path); or oldname is a directory and newname specifies a different path.
ENOENT: File or path specified by oldname not found.
EINVAL: Name contains invalid characters.