Removing Files

You delete files under UNIX using the unlink(2) system call. The function synopsis for it is as follows:

#include <unistd.h>

int unlink(const char *pathname);

A UNIX file can have more than one name linked to a copy of the file. When the last link is removed, the file itself is deleted and the disk space is returned to the file system for re-use.

The function returns -1 if it fails and leaves the error code in errno. Upon a successful return, the value 0 is returned.

The following example code shows how the pathname /tmp/12345.tmp is deleted from a C program:

if ( unlink("/tmp/12345.tmp") == -1 ) {
    fprintf(stderr,"%s: removing /tmp/12345.tmp
",strerror(errno));
    abort();
}

All links to the same file must be released this way before the disk space is returned to the file system.

Warning

The unlink(2) call can take a long time to delete a large file. Time is required to update many internal file system blocks and pointers. Consequently, on some UNIX platforms the unlink(2) call can return the error EINTR (SGI IRIX 6.5 for example).


Note

Note that if any links remain for the file, the file's stat(2) value st_ctime (create time) is updated. The stat(2) values st_ctime and st_mtime (time last modified) are updated for the directory containing the link that was removed.


In addition to the unlink(2) function, the programmer has the remove(3) function, which was formalized by the ISO 9899: 1990 ("ISO C") standard. Its function synopsis is as follows:

#include <stdio.h>

int remove(const char *path);

The remove(3) function differs from unlink(2) in that it is able to remove a file or an empty directory. remove(3) calls upon unlink(2) or rmdir(2) as appropriate. When argument path is a directory, the function rmdir(2) is called. Otherwise, unlink(2) is called. rmdir(2) is described in Chapter 7, "Directory Management."

When remove(3) is successful, the value 0 is returned. Otherwise -1 is returned and the error code is left in global variable errno. For a list of error codes possible, consult the functions unlink(2) and rmdir(2).

Note

While remove(3) is able to remove a directory, it does require that it be empty. This restriction is due to limitation of rmdir(2).


..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
18.217.108.11