C Library Function - rename()
rename() is used in the C standard library toRename a file or directory.
rename() in
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
- old_filename -- The original filename (a full path must be provided if it includes a path).
- new_filename -- new_filename: The new filename (which may also include a path).
Return Value
- 0: Success (the file/directory was renamed successfully).
- Nonzero: Failure (common causes include insufficient permissions, the file not existing, the target already existing, etc.).
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:
- On most Unix/Linux systems, rename() directly overwrites the target file.
- On Windows, if the target file exists, rename() fails.
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 -