Go to the previous, next section.

Deleting Files

You can delete a file with the functions unlink or remove. (These names are synonymous.)

Deletion actually deletes a file name. If this is the file's only name, then the file is deleted as well. If the file has other names as well (see section Hard Links), it remains accessible under its other names.

Function: int unlink (const char *filename)

The unlink function deletes the file name filename. If this is a file's sole name, the file itself is also deleted. (Actually, if any process has the file open when this happens, deletion is postponed until all processes have closed the file.)

The function unlink is declared in the header file `unistd.h'.

This function returns 0 on successful completion, and -1 on error. In addition to the usual file name syntax errors (see section File Name Errors), the following errno error conditions are defined for this function:

EACCESS
Write permission is denied for the directory from which the file is to be removed.

EBUSY
This error indicates that the file is being used by the system in such a way that it can't be unlinked. Examples of situations where you might see this error are if the file name specifies the root directory or a mount point for a file system.

ENOENT
The file name to be deleted doesn't exist.

EPERM
On some systems, unlink cannot be used to delete the name of a directory, or can only be used this way by a privileged user. To avoid such problems, use rmdir to delete directories.

EROFS
The directory in which the file name is to be deleted is on a read-only file system, and can't be modified.

Function: int remove (const char *filename)

The remove function is another name for unlink. remove is the ANSI C name, whereas unlink is the POSIX.1 name. The name remove is declared in `stdio.h'.

Function: int rmdir (const char *filename)

The rmdir function deletes a directory. The directory must be empty before it can be removed; in other words, it can only contain entries for `.' and `..'.

In most other respects, rmdir behaves like unlink. There are two additional errno error conditions defined for rmdir:

EEXIST
ENOTEMPTY
The directory to be deleted is not empty.

These two error codes are synonymous; some systems use one, and some use the other.

The prototype for this function is declared in the header file `unistd.h'.

Go to the previous, next section.