C <stdio.h> - rename() Function
The C <stdio.h> rename() function is used to change the name of a file. The file is identified by character string pointed to by oldname. The new filename is identified by character string pointed to by newname. If newname already exists, the behavior of this function is implementation-defined.
Syntax
int rename ( const char * oldname, const char * newname );
Parameters
oldname |
Specify a pointer to a null-terminated string containing the name of the file to be renamed. The value shall include a path identifying the file to delete. |
newname |
Specify a pointer to a null-terminated string containing the new name of the file. The value shall include the path of the file. |
Return Value
Returns 0 if the file is successfully renamed, otherwise non-zero value is returned.
On most library implementations, the errno variable is also set to a system-specific error code on failure.
Example:
Lets assume that we have a file called test.txt. The example below shows how to use rename() function is used to change the name of this file.
#include <stdio.h> int main (){ int result; char oldname[] = "test.txt"; char newname[] = "test123.txt"; //trying to rename the file result = rename(oldname, newname); //displaying the message if(result == 0) printf("File is successfully renamed."); else printf("Some error has occurred."); return 0; }
If the file is renamed successfully, the following message will be shown:
File is successfully renamed.
Otherwise, the following message will be shown:
Some error has occurred.
❮ C <stdio.h> Library