The unlink
system call in Linux is used to delete (remove) a file from the file system. Once a file is unlinked, it is removed from the directory structure, and its data blocks are marked as available for reuse. However, if a process has the file open, the file’s data remains accessible until the last file descriptor is closed. Here’s how the unlink
system call is used:
Syntax:
int unlink(const char *pathname);
Parameters:
pathname
: The path to the file you want to unlink (delete).
Return Value:
- On success, the
unlink
function returns0
. - On failure, it returns
-1
, and you can use theerrno
variable to determine the specific error.
Example usage:
Suppose you have a file named “example.txt” that you want to delete:
#include <stdio.h>
#include <stdlib.h>
#include <errno.h>
int main() {
const char *filename = "example.txt";
// Unlink (delete) the file
if (unlink(filename) == -1) {
perror("Error unlinking file");
return 1;
}
printf("File '%s' unlinked successfully.\n", filename);
return 0;
}
In this example, the program uses the unlink
function to delete the file named “example.txt”. After calling unlink
, the file will be removed from the file system, and any subsequent attempts to access it will result in an error. Keep in mind that once a file is unlinked, it cannot be recovered using normal means, so use this operation carefully.