Home > Backend Development > C++ > body text

C program uses rename() function to change file name

WBOY
Release: 2023-09-21 22:01:02
forward
1802 people have browsed it

C program uses rename() function to change file name

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);
Copy after login

Function of the rename() function

  • 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.

Algorithm

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.
Copy after login

Program

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;
}
Copy after login

Output

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
Copy after login

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!

source:tutorialspoint.com
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template