The rename function changes a file or directory from its old name to its new name. This operation is similar to the move operation. So we can also use this rename function to move files.
This function exists in the stdio.h library header file.
The syntax of the rename function is as follows:
int rename(const char * oldname, const char * newname);
It accepts two parameters. One is oldname and the other is newname.
Both parameters are pointers to constant characters used to define the old and new names of the file.
If the file is renamed successfully, zero is returned; otherwise, a non-zero integer is returned.
During the rename operation, if the newname file already exists, replace the existing file with this new file.
Refer to the algorithm given below and use the rename() function to change the file name.
Step 1 - Declare variables
Step 2 - Enter the old file path
Step 3 - Enter the new file path
Step 4 - Check rename(old , new) == 0
If yes print file renamed successfully Else Unable to rename.
The following is a C program that uses the rename() function to change the file name -
Live demonstration
#include <stdio.h> int main(){ char old[100], new[100]; printf("Enter old file path: "); scanf("%s", old); printf("Enter new file path: "); scanf("%s", new); if (rename(old, new) == 0){ printf("File renamed successfully.</p><p>"); } else{ printf("Unable to rename files</p><p>"); } return 0; }
When the above program is executed, it produces the following results −
Run 1: Enter old file path: test.exe Enter new file path: test1.exe File renamed successfully. Run 2: Enter old file path: priya.c Enter new file path: bhanu.c Unable to rename files
The above is the detailed content of C program uses rename() function to change file name. For more information, please follow other related articles on the PHP Chinese website!