rename function is used to change a file's name.
Preliminary: | MT-Safe | AS-Safe | AC-Safe | See POSIX Safety Concepts.
renamefunction renames the file oldname to newname. The file formerly accessible under the name oldname is afterwards accessible as newname instead. (If the file had any other names aside from oldname, it continues to have those names.)
The directory containing the name newname must be on the same file system as the directory containing the name oldname.
One special case for
renameis when oldname and newname are two names for the same file. The consistent way to handle this case is to delete oldname. However, in this case POSIX requires that
renamedo nothing and report success—which is inconsistent. We don't know what your operating system will do.
If oldname is not a directory, then any existing file named newname is removed during the renaming operation. However, if newname is the name of a directory,
renamefails in this case.
If oldname is a directory, then either newname must not exist or it must name a directory that is empty. In the latter case, the existing directory named newname is deleted first. The name newname must not specify a subdirectory of the directory
oldnamewhich is being renamed.
One useful feature of
renameis that the meaning of newname changes “atomically” from any previously existing file by that name to its new meaning (i.e., the file that was called oldname). There is no instant at which newname is non-existent “in between” the old meaning and the new meaning. If there is a system crash during the operation, it is possible for both names to still exist; but newname will always be intact if it exists at all.
renamefails, it returns
-1. In addition to the usual file name errors (see File Name Errors), the following
errnoerror conditions are defined for this function:
- One of the directories containing newname or oldname refuses write permission; or newname and oldname are directories and write permission is refused for one of them.
- A directory named by oldname or newname is being used by the system in a way that prevents the renaming from working. This includes directories that are mount points for filesystems, and directories that are the current working directories of processes.
- The directory newname isn't empty. GNU/Linux and GNU/Hurd systems always return
ENOTEMPTYfor this, but some other systems return
- oldname is a directory that contains newname.
- newname is a directory but the oldname isn't.
- The parent directory of newname would have too many links (entries).
- The file oldname doesn't exist.
- The directory that would contain newname has no room for another entry, and there is no space left in the file system to expand it.
- The operation would involve writing to a directory on a read-only file system.
- The two file names newname and oldname are on different file systems.