Easy Tutorial
❮ C Examples Largest Number Three C Function Strcmp ❯

C Library Function - rename()

C Standard Library - <stdio.h>

Description

The C library function int rename(const char *oldfilename, const char *newfilename) renames the file pointed to by oldfilename to newfilename.

Declaration

Here is the declaration for the rename() function.

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

Parameters

Return Value

On success, it returns zero. On error, it returns -1 and sets errno.

Example

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

#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: unable to rename the file");
   }

   return(0);
}

Assuming we have a text file file.txt with the following content. We will use the above program to rename this file. Let's compile and run the above program, which will produce the following message and the file will be renamed to newfile.txt.

File renamed successfully

C Standard Library - <stdio.h>

❮ C Examples Largest Number Three C Function Strcmp ❯