;
主要函数: stat(),opendir(),readdir(),
主要结构体:struct dirent 和 struct stat
主要宏:S_ISDIR(), S_ISREG()
函数 stat()用于获取一个文件路径的信息,并把获取到的信息放到结构体 struct stat 中
函数 opendir()用于生成一个目录指针DIR
函数readdir()用于读取目录指针 DIR 中的信息,返回的值为一个 struct dirent 结构体
结构体struct dirent 用于保存一个目录的属性。这里用到的只是该结构体的 d_name 成员,用于保存目录下的文件名
结构体 struct stat 用于保存 一个文件路径的信息
宏S_ISDIR()用于判断一个文件路径是不是一个目录,是则返回1,否则返回0
宏S_ISREG()用于判断一个文件路径是不是一个普通文件,是则返回1,否则返回0
1 #include <stdio.h>
2 #include <dirent.h>
3 #include <stdlib.h>
4 #include <string.h>
5 #include <sys/types.h>
6 #include <sys/stat.h>
8 int main(int argc, char const *argv[])
10 char const*path = argv[1];
11 struct stat s_buf;
13 /*获取文件信息,把信息放到s_buf中*/
14 stat(path,&s_buf);
16 /*判断输入的文件路径是否目录,若是目录,则往下执行,分析目录下的文件*/
17 if(S_ISDIR(s_buf.st_mode))
18 {
19 printf("[%s] it is a dir\n",path);
20 struct dirent *filename;
21 DIR *dp = opendir(path);
23 /*readdir()必须循环调用,要读完整个目录的文件,readdir才会返回NULL
24 若未读完,就让他循环*/
25 while(filename = readdir(dp))
26 {
27 /*判断一个文件是目录还是一个普通文件*/
28 char file_path[200];
29 bzero(file_path,200);
30 strcat(file_path,path);
31 strcat(file_path,"/");
32 strcat(file_path,filename->d_name);
34 /*获取文件信息,把信息放到s_buf中*/
35 stat(file_path,&s_buf);
37 /*判断是否目录*/
38 if(S_ISDIR(s_buf.st_mode))
39 {
40 printf("[%s] is a dir\n",file_path);
41 }
43 /*判断是否为普通文件*/
44 if(S_ISREG(s_buf.st_mode))
45 {
46 printf("[%s] is a regular file\n",file_path);
47 }
48 }
49 }
51 /*若输入的文件路径是普通文件,则打印并退出程序*/
52 else if(S_ISREG(s_buf.st_mode))
53 {
54 printf("[%s] is a regular file\n",path);
55 return 0;
56 }
58 return 0;