如何在Linux中从C程序创建硬链接

3
我们知道在Linux中可以使用“ln file1 file2”创建硬链接,这将使“file2”成为“file1”的硬链接。
但是当我尝试使用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是所需的硬链接。

有人能指出我在这里犯了什么错误吗?

谢谢。


3
可能会有所帮助:man 2 link - chrk
2个回答

11

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而不是外部shell工具的好处包括显著提高性能和消除标志注入。


int linRet = link(argv[2], argv[3]); if (linRet == 0) return 1; File* fp = fopen(argv[3], "r"); if (fp != NULL) printf("为文件 %s 创建硬链接 %s ,感谢您的帮助。\n", argv[2], argv[3]); - sps

3
根据您提供的测试输入,
$ ./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]的时候最好先检查argc是否等于n+1,这样更加稳妥可靠。


谢谢。不知道我怎么错过了它! - sps

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接