C Library - rename() function



The C library rename(const char *old_filename, const char *new_filename) function causes the filename referred to by old_filename to be changed to new_filename.

Syntax

Following is the C library syntax of the rename() function −

int rename(const char *old_filename, const char *new_filename);

Parameters

This function accepts the two parameters −

  • old_filename:A pointer to a null-terminated string that specifies the name of the file to be renamed. This is the current name of the file.
  • new_filename: A pointer to a null-terminated string that specifies the new name for the file. This is the name you want to give to the file.

Return Value

The rename function returns both integer or non-integer value:

1. 0: If the operation is successful.

2. Non-zero value: If the operation fails. The exact value can vary, but in general, you can use errno to get more information about the error. Common errors include:

  • EACCES: Permission denied.
  • ENOENT: File specified by old_filename does not exist.
  • EEXIST: A file with the name specified by new_filename already exists.
  • EINVAL: The names specified are invalid.

Example 1: Simple Rename

This example renames a file named oldfile.txt to newfile.txt.

Below is the illustration of the C library rename() function.

#include <stdio.h>

int main() {
   if (rename("oldfile.txt", "newfile.txt") == 0) {
       printf("File renamed successfully.\n");
   } else {
       perror("Error renaming file");
   }
   return 0;
}

Output

The above code produces following result−

File renamed successfully.

Example 2: Rename with Error Handling

This example attempts to rename a non-existent file, demonstrating error handling and usage of errno.

#include <stdio.h>
#include <errno.h>

int main() {
   if (rename("nonexistentfile.txt", "newname.txt") != 0) {
       perror("Error renaming file");
       printf("Error code: %d\n", errno);
   } else {
       printf("File renamed successfully.\n");
   }
   return 0;
}

Output

After execution of above code, we get the following result

Error renaming file: No such file or directory
Error code: 2