1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99
| #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("=== Unlink函数示例 ===\n"); // 示例1: 基本文件删除 printf("示例1: 基本文件删除\n"); // 创建测试文件 fd = open("test_unlink.txt", O_CREAT | O_WRONLY, 0644); if (fd != -1) { write(fd, "Test content for unlink", 23); close(fd); printf("创建测试文件\n"); } // 删除文件 if (unlink("test_unlink.txt") == -1) { perror("删除文件失败"); } else { printf("成功删除文件\n"); // 验证文件已删除 if (access("test_unlink.txt", F_OK) == -1) { printf("文件确实已删除\n"); } } // 示例2: 硬链接删除演示 printf("示例2: 硬链接删除演示\n"); // 创建文件和硬链接 fd = open("multi_link.txt", O_CREAT | O_WRONLY, 0644); if (fd != -1) { write(fd, "Content with multiple links", 27); close(fd); } if (link("multi_link.txt", "second_link.txt") == 0) { printf("创建硬链接\n"); // 检查链接数 if (stat("multi_link.txt", &st) == 0) { printf("当前链接数: %ld\n", st.st_nlink); } // 删除一个链接 if (unlink("second_link.txt") == 0) { printf("删除一个链接\n"); if (stat("multi_link.txt", &st) == 0) { printf("剩余链接数: %ld\n", st.st_nlink); printf("文件数据仍然存在\n"); } } } // 示例3: 文件被打开时的删除 printf("示例3: 文件被打开时的删除\n"); fd = open("open_file.txt", O_CREAT | O_WRONLY, 0644); if (fd != -1) { write(fd, "Content of open file", 20); printf("创建并打开文件\n"); // 删除已打开的文件 if (unlink("open_file.txt") == 0) { printf("删除已打开的文件(文件仍可访问)\n"); // 仍可以读写文件 lseek(fd, 0, SEEK_SET); char buffer[50]; int n = read(fd, buffer, sizeof(buffer)); if (n > 0) { buffer[n] = '\0'; printf("文件内容: %s\n", buffer); } // 关闭文件后,数据才真正删除 close(fd); printf("关闭文件后,数据真正删除\n"); } } // 清理剩余文件 unlink("multi_link.txt"); return 0; }
|