3

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.

sps
  • 2,720
  • 2
  • 19
  • 38

2 Answers2

11

Shell scripting knowledge rarely transfers well to C programming. Here's man 2 link which you should be using instead:

NAME
       link - make a new name for a file

SYNOPSIS
       #include <unistd.h>

       int link(const char *oldpath, const char *newpath);

Benefits of using the C api instead of external shell tools include a dramatic performance increase and elimination of flag injection.

that other guy
  • 116,971
  • 11
  • 170
  • 194
  • int linRet = link ( argv[2] , argv[3] ) ; if (linkRet==0) return 1 ; File *fp = fopen (argv[3], "r"); if (fp != NULL) printf (" hardlink %s for file %s \nthanks for help,\n",argv[3],argv[2]); – sps Apr 07 '15 at 04:26
3

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.

Sourav Ghosh
  • 133,132
  • 16
  • 183
  • 261