Private archive copy · Unofficial site · Content copyright belongs to Runoob Tutorial and the original authors · View Original

C Library Function - rename()

C Library Function - rename()

C Standard Library - <stdio.h> C Standard Library -

rename() is used in the C standard library toRename a file or directory.

rename() in header file.

C Library Function **int rename(const char old_filename, const char new_filename) Puts the old_filename changes the filename pointed to by to a new name new_filename.

Declaration

The following is the declaration of the rename() function.



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

Parameters

Return Value

Usage notes

The file must exist, otherwise an error is returned.

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

Renaming across different mount points (partitions/devices) is not allowed.


Example

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

Example

#include

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 file file.txt, whose contents are as follows. 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 files.



文件重命名成功

C Standard Library - <stdio.h> C Standard Library -