2015-04-06 153 views
1

我们知道我们可以在Linux中使用ln file1 file2创建硬链接,这将使得file2成为file1的硬链接。如何从C程序在Linux中创建硬链接

但是,当我尝试通过使用C程序来做到这一点时,我遇到了问题。以下是C代码。

#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; 
} 

用gcc编译这个程序后,我运行它如下。

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

file1这里存在并且file2是所希望的硬链接。

任何人都可以指出我在这里犯了什么错误。

谢谢。

+2

[man 2 link](http://linux.die.net/man/2/link)可能会有帮助。 – chrk

回答

2

按照由你

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

在你的代码所示的测试输入

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

应该读

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

这就是说,它始终是更好,建议使用argv[n]检查后argcn+1

+0

谢谢。不知道我错过了它! – sps

6

Shell脚本知识很少转移到C编程。这里是man 2 link,你应该使用来代替:

NAME 
     link - make a new name for a file 

SYNOPSIS 
     #include <unistd.h> 

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

使用C API,而不是外壳工具包括一个显着的性能提升和消除国旗注射的好处。

+0

感谢您的帮助! – sps

+0

int linRet = link(argv [2],argv [3]); if(linkRet == 0)返回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