Search code examples
clinuxexecvphardlink

How to create hard link in Linux from a C program


We know we can create hard link in Linux using ln file1 file2 which will make file2 a hard link of file1.

However when I try to do this by using a C program, I face issues. Below is the C code.

#include<stdio.h>
#include<string.h>
#include<unistd.h>

int main(int argc, char *argv[])
{
    if ((strcmp (argv[1],"ln")) == 0 )
    {
            char *myargs[4];
            myargs[0] = "ln";
            myargs[1] = argv[3];
            myargs[2] = argv[4];
            myargs[3] = NULL;
            execvp(myargs[0], myargs);
            printf("Unreachable code\n");
    }
    return 0;
}

After compiling this program with gcc I run it as below.

$ ./a.out ln file1 file2
ln: failed to access ‘file2’: No such file or directory
$       

Here file1 exists and file2 is the desired hardlink.

Could anyone point where did I make mistake here.

Thanks.


Solution

  • As per the test input shown by you

    $ ./a.out     ln      file1     file2
        ^         ^        ^         ^
        |         |        |         |
      argv[0]  ..[1]    ..[2]     ..[3]
    

    in your code

            myargs[1] = argv[3];
            myargs[2] = argv[4];
    

    should read

            myargs[1] = argv[2];
            myargs[2] = argv[3];
    

    That said, it is always better and advisable to use the argv[n] after checking argc against n+1.