NO.7 Linux 获取文件属性

发布时间 2023-10-01 06:24:15作者: 真是服了你个老六!!
 1 /*
 2 用于获取文件的属性和元数据信息,并输出到终端。
 3 程序接受一个参数作为路径名,通过lstat函数获取指定文件的属性信息,并使用printf函数输出到终端。
 4 注释对代码进行了简要解释,帮助理解各个部分的功能。
 5 */
 6 #include <sys/types.h>
 7 #include <sys/stat.h>
 8 #include <stdint.h>
 9 #include <time.h>
10 #include <stdio.h>
11 #include <stdlib.h>
12 #include <sys/sysmacros.h>
13 
14 int main(int argc, char *argv[])
15 {
16     struct stat sb;
17 
18     // 检查参数数量
19     if (argc != 2) {
20         fprintf(stderr, "Usage: %s <pathname>\n", argv[0]);
21         exit(EXIT_FAILURE);
22     }
23 
24     // 获取文件属性
25     if (lstat(argv[1], &sb) == -1) {
26         perror("lstat");
27         exit(EXIT_FAILURE);
28     }
29 
30     // 输出所属设备ID
31     printf("ID of containing device:  [%jx,%jx]\n",
32             (uintmax_t) major(sb.st_dev),
33             (uintmax_t) minor(sb.st_dev));
34 
35     printf("File type:                ");
36 
37     // 输出文件类型
38     switch (sb.st_mode & S_IFMT) {
39     case S_IFBLK:  printf("block device\n");            break;
40     case S_IFCHR:  printf("character device\n");        break;
41     case S_IFDIR:  printf("directory\n");               break;
42     case S_IFIFO:  printf("FIFO/pipe\n");               break;
43     case S_IFLNK:  printf("symlink\n");                 break;
44     case S_IFREG:  printf("regular file\n");            break;
45     case S_IFSOCK: printf("socket\n");                  break;
46     default:       printf("unknown?\n");                break;
47     }
48 
49     printf("I-node number:            %ju\n", (uintmax_t) sb.st_ino);
50 
51     // 输出文件权限模式
52     printf("Mode:                     %jo (octal)\n",
53             (uintmax_t) sb.st_mode);
54 
55     // 输出链接数
56     printf("Link count:               %ju\n", (uintmax_t) sb.st_nlink);
57     
58     // 输出文件所有者信息
59     printf("Ownership:                UID=%ju   GID=%ju\n",
60             (uintmax_t) sb.st_uid, (uintmax_t) sb.st_gid);
61 
62     // 输出首选I/O块大小
63     printf("Preferred I/O block size: %jd bytes\n",
64             (intmax_t) sb.st_blksize);
65     
66     // 输出文件大小
67     printf("File size:                %jd bytes\n",
68             (intmax_t) sb.st_size);
69     
70     // 输出分配的块数
71     printf("Blocks allocated:         %jd\n",
72             (intmax_t) sb.st_blocks);
73 
74     // 输出最后状态更改时间
75     printf("Last status change:       %s", ctime(&sb.st_ctime));
76     
77     // 输出最后访问文件的时间
78     printf("Last file access:         %s", ctime(&sb.st_atime));
79     
80     // 输出最后修改文件的时间
81     printf("Last file modification:   %s", ctime(&sb.st_mtime));
82 
83     exit(EXIT_SUCCESS);
84 }