Open In App

C program to create hard link and soft link

Improve
Improve
Like Article
Like
Save
Share
Report

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:

C




// C program to create an Hard Link
// to the existing file
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
  
// Driver Code
int main(int argc, char* argv[])
{
    // Link function
    int l = link(argv[1], argv[2]);
  
    // argv[1] is existing file name
    // argv[2] is link file name
    if (l == 0) {
        printf("Hard Link created"
               " succuessfuly");
    }
  
    return 0;
}


Output:

Program 2: Below is the C program to create a Soft link to an existing file:

C




// C program to create an Soft Link
// to the existing file
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
  
// Driver Code
int main(int argc, char* argv[])
{
    // Symlink function
    int sl = symlink(argv[1], argv[2]);
  
    // argv[1] is existing file name
    // argv[2] is soft link file name
    if (sl == 0) {
        printf("Soft Link created"
               " succuessfuly");
    }
  
    return 0;
}


Output:



Last Updated : 30 Nov, 2021
Like Article
Save Article
Previous
Next
Share your thoughts in the comments
Similar Reads