Imran Shafqat
Imran Shafqat

Reputation: 518

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.

Upvotes: 8

Views: 16953

Answers (6)

harper
harper

Reputation: 13690

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.

Upvotes: 2

Alex
Alex

Reputation: 1641

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:

Upvotes: 12

4pie0
4pie0

Reputation: 29724

If you are on Linux you can simply display string representation of error just after fatal call to rename while in gdb:

211             if (rename(f_z_name, y) == -1) {
(gdb) n
212                 err = RM_ERR_RENAME_TMP_Y;
(gdb) p errno
$6 = 18
(gdb) p strerr(errno)
No symbol "strerr" in current context.
(gdb) p strerror(errno)
$7 = 0x7ffff7977aa2 "Invalid cross-device link"
(gdb) 

Upvotes: 1

user1098761
user1098761

Reputation: 579

if the file is open, please close it before change the name. The code below won't work and the file name can't be changed.

ofstream _file("C:\\yourfile.txt", ofstream::app); 

if (-1 == rename("C:\\yourfile.txt", "C:\\yourfile2.txt"))
     puts("The file doesn't exist or already deleted");

_file.close();

Upvotes: -2

Matthew Walton
Matthew Walton

Reputation: 9959

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.

Upvotes: 3

shf301
shf301

Reputation: 31394

rename will set the _errno global variable with the last error number, check that.

Upvotes: 1

Related Questions