Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 881
Imran Shafqat Avatar asked Sep 06 '12 11:09

Imran Shafqat


People also ask

Why can I not rename a file?

When a file or folder is still open, Windows doesn't allow users to rename it. Therefore, you must ensure that no files or folders are open and no apps are running in the background while you're renaming. To do that, simply click on the same file again to open it, and it will take you to the already opened tab.

What is the purpose of the rename () function when creating a file?

rename() function is used to change the name of the file or directory i.e. from old_name to new_name without changing the content present in the file. This function takes name of the file as its argument.

What is the method of rename () a file?

Find and select the file, then select File > Rename. Type the new name and press Enter.

What method will rename a file the fastest?

We feel the F2 keyboard shortcut is the fastest way to rename a bunch of files, whether you are trying to add different names for each of them or change all their names in one go.


1 Answers

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)
like image 170
Alex Avatar answered Oct 19 '22 06:10

Alex