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

故事扮演 提交于 2019-12-23 09:30:07

问题


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.


回答1:


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 returned errors probably are OS-specific. http://linux.die.net/man/3/rename shows what you typically can get, when using linux.




回答2:


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.




回答3:


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




回答4:


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.



回答5:


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) 



回答6:


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


来源:https://stackoverflow.com/questions/12299495/rename-returns-1-how-to-know-why-rename-fails

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!