函数介绍 链接到标题

link系统调用用于创建文件的硬链接。硬链接是指向同一inode的多个目录项,多个文件名指向同一个文件数据。

函数原型 链接到标题

#include <unistd.h>

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

功能 链接到标题

为现有文件创建一个新的硬链接(文件名)。

参数 链接到标题

  • const char *oldpath: 现有文件的路径
  • const char *newpath: 新链接的路径

返回值 链接到标题

  • 成功时返回0
  • 失败时返回-1,并设置errno

特殊限制 链接到标题

  • 不能跨文件系统创建硬链接
  • 不能为目录创建硬链接(除.和..外)
  • 目标文件不能已存在

相似函数 链接到标题

  • symlink(): 创建符号链接
  • linkat(): 相对路径版本

示例代码 链接到标题

#define _GNU_SOURCE
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <fcntl.h>
#include <errno.h>
#include <string.h>
#include <sys/stat.h>

int main() {
    int fd;
    struct stat st;
    
    printf("=== Link函数示例 ===\n");
    
    // 示例1: 基本硬链接创建
    printf("示例1: 基本硬链接创建\n");
    
    // 创建原始文件
    fd = open("original.txt", O_CREAT | O_WRONLY, 0644);
    if (fd != -1) {
        write(fd, "Hard link test content", 22);
        close(fd);
        printf("创建原始文件: original.txt\n");
    }
    
    // 创建硬链接
    if (link("original.txt", "hardlink.txt") == -1) {
        perror("创建硬链接失败");
    } else {
        printf("创建硬链接: hardlink.txt -> original.txt\n");
        
        // 验证硬链接(检查inode号相同)
        if (stat("original.txt", &st) == 0) {
            printf("原始文件inode: %ld\n", st.st_ino);
            printf("原始文件链接数: %ld\n", st.st_nlink);
        }
        
        if (stat("hardlink.txt", &st) == 0) {
            printf("硬链接文件inode: %ld\n", st.st_ino);
            printf("硬链接文件链接数: %ld\n", st.st_nlink);
        }
    }
    
    // 示例2: 硬链接特性演示
    printf("示例2: 硬链接特性演示\n");
    
    // 通过任一链接修改文件
    fd = open("hardlink.txt", O_WRONLY | O_APPEND);
    if (fd != -1) {
        write(fd, "\nModified through hard link", 26);
        close(fd);
        printf("通过硬链接修改文件内容\n");
    }
    
    // 通过原始文件读取验证
    fd = open("original.txt", O_RDONLY);
    if (fd != -1) {
        char buffer[100];
        ssize_t n = read(fd, buffer, sizeof(buffer) - 1);
        if (n > 0) {
            buffer[n] = '\0';
            printf("通过原始文件读取内容:\n%s\n", buffer);
        }
        close(fd);
    }
    
    // 示例3: 错误处理
    printf("示例3: 错误处理\n");
    
    // 尝试为不存在的文件创建硬链接
    if (link("nonexistent.txt", "link_to_nothing") == -1) {
        printf("为不存在文件创建硬链接: %s\n", strerror(errno));
    }
    
    // 尝试创建已存在的文件链接
    if (link("original.txt", "hardlink.txt") == -1) {
        printf("创建重复硬链接: %s\n", strerror(errno));
    }
    
    // 清理测试文件
    unlink("original.txt");
    unlink("hardlink.txt");
    
    return 0;
}