Skip to content
Related Articles

Related Articles

Improve Article
Save Article
Like Article

C program to create hard link and soft link

  • Last Updated : 30 Nov, 2021

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.

Take a step-up from those "Hello World" programs. Learn to implement data structures like Heap, Stacks, Linked List and many more! Check out our Data Structures in C course to start learning today.

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:




My Personal Notes arrow_drop_up
Recommended Articles
Page :

Start Your Coding Journey Now!