Search code examples
c++renamefile-rename

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


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.


Solution

  • 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: