C program to create hard link and soft link
There are two types of links, i.e., a soft link and a hard link to a file. C library has a function link() that creates a new hard link to an existing file. The function symlink() to create a soft link. If the link file/path already exists, it will not be overwritten. Both function link() and symlink() return 0 on success. If any error occurs, then -1 is returned. Otherwise, ‘errno’ (Error Number) is set appropriately.
Soft Link: A soft link (also known as a Symbolic link) acts as a pointer or a reference to the file name. It does not access the data available in the original file. If the earlier file is deleted, the soft link will point to a file that does not exist anymore.
Hard Link: A hard link acts as a copy (mirrored) of the selected file. It accesses the data available in the original file.
If the earlier selected file is deleted, the hard link to the file will still contain the data of that file.
Function to create a Hard Link:
L = link(FILE1, FILE2), creates a hard link named FILE2 to an existing FILE1.
where, L is the value returned by the link() function.
Function to create a Soft Link:
sL = symlink(FILE1, FILE2), creates a soft link named FILE2 to an existing FILE1.
where, sL is the value returned by the symlink() function
Program 1: Below is the C program to create a hard link to an existing file:
Program 2: Below is the C program to create a Soft link to an existing file: