25. link - 创建硬链接 見出しへのリンク
函数介绍 見出しへのリンク
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;
}