通过lstat函数获取文件的类型的代码如下。
1 #include "apue.h"
2
3 int main(int argc,char *argv[])
4 {
5 int i;
6 struct stat buf;
7 char *ptr;
8
9 for(i = 1;i < argc;i++){
10 printf("%s: ",argv[i]);
11 if(lstat(argv[i],&buf) < 0){
12 err_ret("lstat error");
13 continue;
14 }
15 if(S_ISREG(buf.st_mode))
16 ptr = "regular";
17 else if(S_ISDIR(buf.st_mode))
18 ptr = "directory";
19 else if(S_ISCHR(buf.st_mode))
20 ptr = "character special";
21 else if(S_ISBLK(buf.st_mode))
22 ptr = "block special";
23 else if(S_ISFIFO(buf.st_mode))
24 ptr = "fifo";
25 else if(S_ISLNK(buf.st_mode))
26 ptr = "symbolic link";
27 else if(S_ISSOCK(buf.st_mode))
28 ptr = "socket";
29 else
30 ptr = "** unkonwn mode **";
31
32 printf("%s\r\n",ptr);
33 }
34
35 return 0;
36
执行文件之后的显示结果如下:通过lstat函数可以正确的获取文件的类型