C Library Functions -rename()

C Standard Library - <stdio.h>

rename() is a C standard library function used forRename file or directoryof the function.

rename() is defined in the <stdio.h> header file.

C Library Functionsint rename(const char *old_filename, const char *new_filename)holdold_filenameThe name of the file it points to is changed tonew_filename。

Declaration

Below is the declaration of the rename() function.

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

Parameter

  • old_filename-- The original filename (if it contains a path, the full path must be provided).
  • new_filename-- new_filename: the new filename (can also contain a path).

Return Value

  • 0: Execution successful (file/directory renamed successfully).
  • Non-zero: execution failure (common error causes include insufficient permissions, file does not exist, target already exists, etc.).

Usage notes

The file must exist; otherwise, an error will be returned.

If the target file new_filename already exists, different systems may handle it differently:

  • On most Unix/Linux systems, rename() will directly overwrite the target file.
  • On Windows, if the target file exists, rename() will fail.

Cannot rename across different mount points (partitions/devices).


Example

The following example demonstrates the usage of the rename() function.

Example

#include <stdio.h>

int main () {
   int ret;
   char oldname[] = "file.txt";
   char newname[] = "newfile.txt";
   
   ret = rename(oldname, newname);

   if(ret == 0)  {
      printf("File renamed successfully");
   } else   {
      printf("Error: cannot rename the file");
   }
   
   return(0);
}

Suppose we have a text filefile.txt, whose contents are as follows. We will use the above program to rename the file. Let us compile and run the above program, which will generate the following message, and the file will be renamed tonewfile.txtFile.

File renamed successfully.

C Standard Library - <stdio.h>

other extensions