unlink() — Remove a directory entry
Standards
Standards / Extensions | C or C++ | Dependencies |
---|---|---|
POSIX.1
XPG4 XPG4.2 Single UNIX Specification, Version 3 |
both |
Format
#define _POSIX_SOURCE
#include <unistd.h>
int unlink(const char *pathname);
General description
Removes a directory entry. This unlink() deletes the link named by pathname and decrements the link count for the file itself.
pathname can refer to a pathname, a link, or a symbolic link. If the pathname refers to a symbolic link, unlink() removes the symbolic link but not any file or directory named by the contents of the symbolic link.
If the link count becomes 0 and no process currently has the file open, the file itself is deleted. The space occupied by the file is freed for new use, and the current contents of the file are lost. If one or more processes have the file open when the last link is removed, unlink() removes the link, but the file itself is not removed until the last process closes the file.
unlink() cannot be used to remove a directory; use rmdir() instead.
If unlink() succeeds, the change and modification times for the parent directory are updated. If the file's link count is not 0, the change time for the file is also updated. If unlink() fails, the link is not removed.
Returned value
If successful, unlink() returns 0.
- Error Code
- Description
- EACCES
- The process did not have search permission for some component of pathname, or did not have write permission for the directory containing the link to be removed.
- EBUSY
- pathname cannot be unlinked because it is currently being used by the system or some other process.
- ELOOP
- A loop exists in symbolic links. This error is issued if more than POSIX_SYMLOOP symbolic links are detected in the resolution of pathname.
- ENAMETOOLONG
- pathname is longer than PATH_MAX characters, or some component of pathname is longer than NAME_MAX characters while _POSIX_NO_TRUNC is in effect. For symbolic links, the length of the pathname string substituted for a symbolic link exceeds PATH_MAX. The PATH_MAX and NAME_MAX values can be determined using pathconf().
- ENOENT
- pathname does not exist, or it is an empty string.
- ENOTDIR
- Some component of the pathname prefix is not a directory.
- EPERM
- pathname is a directory, and unlink() cannot be used on directories.
- EROFS
- The link to be removed is on a read-only file system.
Example
/* CELEBU06
This example removes a directory entry, using unlink().
*/
#define _POSIX_SOURCE
#include <fcntl.h>
#include <sys/stat.h>
#include <sys/types.h>
#include <unistd.h>
#undef _POSIX_SOURCE
#include <stdio.h>
main() {
int fd;
char fn[]="unlink.file";
if ((fd = creat(fn, S_IWUSR)) < 0)
perror("creat() error");
else {
close(fd);
if (unlink(fn) != 0)
perror("unlink() error");
}
}