Quick links
Write a C program to rename a file using rename() function. How to rename a file using rename() function in C programming. rename() function in C programming.
Required knowledge
Basic Input Output, File handling

rename() function in C
int rename(const char * oldname, const char * newname);rename() function is defined in stdio.h header file. It renames a file or directory from oldname to newname. The rename operation is same as move, hence you can also use this function to move a file.
It accepts two parameter oldname and newname which is pointer to constant character, defining old and new name of file.
It returns zero if file renamed successfully otherwise returns a non-zero integer. During the rename operation if there already exists a file with newname then it replaces the existing file.
Program to rename a file using rename() function
/**
* C program to rename a file using rename() function.
*/
#include <stdio.h>
int main()
{
// Path to old and new files
char oldName[100], newName[100];
// Input old and new file name
printf("Enter old file path: ");
scanf("%s", oldName);
printf("Enter new file path: ");
scanf("%s", newName);
// rename old file with new name
if (rename(oldName, newName) == 0)
{
printf("File renamed successfully.\n");
}
else
{
printf("Unable to rename files. Please check files exist and you have permissions to modify files.\n");
}
return 0;
}Output
Enter old file path: data\file3.txt Enter new file path: data\file3 File renamed successfully. Enter old file path: data\file3.txt Enter new file path: data\file3 Unable to rename files. Please check files exist and you have permissions to modify files.
You can also use it for moving a file from old location to new location.
Output
Enter old file path: data/file3.txt Enter new file path: file3.txt File renamed successfully.
Happy coding 😉