Advanced Programming in the UNIX® Environment

(lily) #1
ptg10805159

Section 4.16 renameandrenameatFunctions 119


The superuser can callunlinkwithpathname specifying a directory if the file
system supports it, but the functionrmdirshould be used instead to unlink a directory.
We describe thermdirfunction in Section 4.21.
We can also unlink a file or a directory with theremovefunction. Forafile,
removeis identical tounlink.For a directory,removeis identical tormdir.

#include <stdio.h>
int remove(const char *pathname);
Returns: 0 if OK,−1 on error

ISO C specifies theremovefunction to delete a file. The name was changed from the historical
UNIX name ofunlinkbecause most non-UNIX systems that implement the C standarddidn’t
support the concept of links to a file at the time.

4.16 renameandrenameat Functions


Afile or a directory is renamed with either therenameorrenameatfunction.

#include <stdio.h>
int rename(const char *oldname,const char *newname);
int renameat(intoldfd,const char *oldname,intnewfd,
const char *newname);
Both return: 0 if OK,−1 on error

Therenamefunction is defined by ISO C for files. (The C standarddoesn’t deal with
directories.) POSIX.1 expanded the definition to include directories and symbolic links.

Thereare several conditions to describe for these functions, depending on whether
oldnamerefers to a file, a directory, or a symbolic link. We must also describe what
happens ifnewnamealready exists.


  1. Ifoldnamespecifies a file that is not a directory,then we arerenaming a file or a
    symbolic link. In this case, ifnewnameexists, it cannot refer to a directory.If
    newnameexists and is not a directory, it is removed, andoldnameis renamed to
    newname.Wemust have write permission for the directory containingoldname
    and the directory containingnewname,since we arechanging both directories.

  2. Ifoldnamespecifies a directory,then we arerenaming a directory.Ifnewname
    exists, it must refer to a directory,and that directory must be empty.(When we
    say that a directory is empty, we mean that the only entries in the directory are
    dot and dot-dot.) Ifnewnameexists and is an empty directory, it isremoved, and
    oldnameis renamed tonewname.Additionally,when we’rerenaming a directory,
    newnamecannot contain a path prefix that namesoldname.For example, we
    can’t rename /usr/foo to /usr/foo/testdir,because the old name
    (/usr/foo) is a path prefix of the new name and cannot be removed.

Free download pdf