C program to change the file name using rename() function


The rename function changes a file or directory from oldname to newname. This operation is just like a move operation. Hence, we can also use this rename function to move a file.

This function is present in stdio.h library header files.

The syntax of rename function is as follows −

int rename(const char * oldname, const char * newname);

Function of rename()

  • It accepts two parameters. One is oldname and another is newname.

  • These two parameters are pointer to constant character, which define old and new name of file.

  • If file renamed is successful, then it returns zero otherwise, it returns a non-zero integer.

  • During the rename operation if that newname file is already present, then it replaces that already existing file with this new file.

Algorithm

Refer an algorithm given below for changing the file name by using rename() function.

Step 1 − Declare variables

Step 2 − Enter old file path

Step 3 − Enter new file path

Step 4 − check rename(old, new) == 0

If yes print file renamed successfully
Else
Unable to rename.

Program

Following is the C program to change the file name by using rename() function

 Live Demo

#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.
");    }    else{       printf("Unable to rename files
");    }    return 0; }

Output

When the above program is executed, it produces the following result −

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

Updated on: 01-Sep-2021

2K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements