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\n",strerror(errno));
    abort();
}

All links to the same file must be released this way ...

Get Advanced UNIX Programming now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.