Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Does the c rename() function delete files?

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:

enter image description here

And this is the contents of the directory that I have after running the rename() function:

enter image description here

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.

like image 285
Adam Bak Avatar asked Dec 07 '22 19:12

Adam Bak


1 Answers

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 by old to be henceforth known by the name given by the string pointed to by new. The file named old is no longer accessible by that name. If a file named by the string pointed to by new 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.

like image 144
AlexD Avatar answered Jan 01 '23 11:01

AlexD