主要用到的函数为stat(),如下:
#include <sys/stat.h>

int stat(const char *pathname, struct stat *buf);
int lstat(const char *pathname, struct stat *buf);
int fstat(int fd, struct stat *buf);

stat()可以解析指定路径下的文件,并把详细信息赋值在传入的参数buf中。
lstat()的功能与stat()几乎是一样的,只是在处理符号链接文件stat()直接跳转并解析链接文件的原文件,而非链接文件本身;而lstat()则是解析链接文件本身。
fstat()的功能与stat()是一样的,只是要解析的文件是通过参数fd来指定的。

实现的代码如下,注释已经写得很明白了。

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
#include <sys/types.h>
#include <sys/stat.h>
#include <time.h>
#include <stdio.h>
#include <stdlib.h>

int main(int argc, char *argv[]) {
struct stat sb;

if (argc != 2) {
fprintf(stderr, "Usage: %s <pathname>\n", argv[0]); // stdio.h
exit(EXIT_FAILURE);
}

if (lstat(argv[1], &sb) == -1) {
perror("stat");// stdio.h
exit(EXIT_FAILURE);
}

printf("File type: ");

// stat.h
// 判断文件类型:文件、文件夹、符号链接文件等其它
switch (sb.st_mode & S_IFMT) {
case S_IFBLK: printf("block device\n"); break;
case S_IFCHR: printf("character device\n"); break;
case S_IFDIR: printf("directory\n"); break;
case S_IFIFO: printf("FIFO/pipe\n"); break;
case S_IFREG: printf("regular file\n"); break;
case S_IFSOCK: printf("socket\n"); break;
// S_IFLNK:使用lstat()时才有效,stat()对symbolic link都会跳转到其原文件进行解析
case S_IFLNK: printf("symlink\n"); break;

default: printf("unknown?\n"); break;
}

printf("I-node number: %ld\n", (long) sb.st_ino);
// 各种 子mode值的或操作值
printf("Mode: %lo (octal)\n", (unsigned long) sb.st_mode);
// 硬链接文件数量,参考:http://sodino.com/2015/03/06/linux-hard-and-symoblic-link/
printf("Link count: %ld\n", (long) sb.st_nlink);
printf("Ownership: UID=%ld GID=%ld\n",
(long) sb.st_uid, (long) sb.st_gid);

// 文件系统为文件所分配的最小硬盘存储空间:4kb。
// 所以虽然文件真实内容可能更小,但在硬盘中仍占用了至少4kb;或者4kb的倍数。
printf("Preferred I/O block size: %ld bytes\n", (long) sb.st_blksize);
// 文件内容的真实大小
printf("File size: %lld bytes\n", (long long) sb.st_size);
// 已分配的block(最小是512bytes)数量,所以这里打印出来是8
printf("Blocks allocated: %lld\n", (long long) sb.st_blocks);

// 最近的访问时间
printf("Last file access: %s", ctime(&sb.st_atime));
// 最近的修改时时间:write、truncate、utime...
printf("Last file modification: %s", ctime(&sb.st_mtime));
// 最近的改变时间:write、owner、group、hard link count...
printf("Last status change: %s", ctime(&sb.st_ctime)); // time.h
exit(EXIT_SUCCESS); // stdlib.h
}

操作见下图:
file_detail_info

验证uid、gid的分组,可以使用id命令:
terminal.uid.gid