The function int rename(const char *oldName, const char *newName); changes the name of the file specified by oldName to newName. It directly renames the file identified by the oldName without any stream operation. If a file with name newName already exists, the rename function may either override the existing file or fail, depending on the implementation.
Function prototype of rename
- oldName : This is a null terminated string containing the name of an existing file to be renamed.
- newName : This is a null terminated string containing the new name of the file.
Return value of rename
On Success, rename function returns zero otherwise in case of an error it returns -1 and sets errno variable to a system-specific error code.
C program to using rename function
The following program shows the use of rename function to rename an exiting file. Below program first creates a file called textFile.txt and then renames it to newTestFile.txt using rename function.
#include <stdio.h> int main (){ int response; FILE *file; /* Create a new file */ file = fopen("textFile.txt", "w"); fputs("TechCrashCourse.com", file); fclose(file); /* Rename textFile.txt to newTextFile.txt */ response = rename("textFile.txt", "newTextFile.txt"); if(response == 0) { printf("textFile.txt renamed to newTextFile.txt\n"); } else { printf("Error: unable to rename textFile.txt"); } return(0); }
Output
textFile.txt renamed to newTextFile.txt