I am practicing programming in the C programming language and was experimenting with the rename()
function. I am using the following code:
#include <stdio.h>
#include <stdlib.h>
int main(void)
{
if(rename ("data", "database") )
{
fprintf(stderr, "Can't rename file\n");
exit(EXIT_FAILURE);
}
return 0;
}
This code changes the name of a file named, "data" to a file named, "database". I was wondering what would happen if you attempted to run this code, but already had a file named "database" in the same directory.
This is the contents of the directory that I have before running the rename()
function:
And this is the contents of the directory that I have after running the rename()
function:
It appears that the rename()
function did correctly rename my file, but it also deleted the file that was already in this directory that had the same name. I was wondering if this is how the rename()
function was designed to work or if this is something that my operating system (Windows 10 - cygwin64 - gcc compiler) is doing. Also, when using this function, should I first check to make sure that there are no files that already have the same name to prevent them from being deleted? Thank you for the help and insight.
You have to consult the documentation of your C library. According to the standard (N1570 7.21.4.2
, emphasis mine):
The
rename
function causes the file whose name is the string pointed to byold
to be henceforth known by the name given by the string pointed to bynew
. The file namedold
is no longer accessible by that name. If a file named by the string pointed to bynew
exists prior to the call to the rename function, the behavior is implementation-defined.
In the case of gcc rename
:
If oldname is not a directory, then any existing file named newname is removed during the renaming operation. However, if newname is the name of a directory, rename fails in this case.
In case of VS, however:
The new name must not be the name of an existing file or directory.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With