C语言判断是文件还是文件夹

 1 root@mkx:~/workspace/learn# cat isFile.c 
 2 //头文件 
 3 #include <stdio.h> 
 4 #include <stdlib.h> 
 5 #include <sys/stat.h> 
 6 //代码 
 7 int main() 
 8 { 
 9   char* fileName = "/tmp/2021/test1"; 
10   struct stat buf; 
11   int result; 
12   result = stat(fileName, &buf); 
13   if(S_IFDIR & buf.st_mode){ 
14     printf("folder\n"); 
15   }else if(S_IFREG & buf.st_mode){ 
16     printf("file\n"); 
17   } 
18  
19   return 0; 
20 } 

 

 

写法二

主要函数: 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>
 7  
 8 int main(int argc, char const *argv[])
 9 {
10     char const*path = argv[1];
11     struct stat s_buf;
12  
13     /*获取文件信息,把信息放到s_buf中*/
14     stat(path,&s_buf);
15  
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);
22  
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);
33             
34             /*获取文件信息,把信息放到s_buf中*/
35             stat(file_path,&s_buf);
36  
37             /*判断是否目录*/
38             if(S_ISDIR(s_buf.st_mode))
39             {
40                 printf("[%s] is a dir\n",file_path);
41             }
42  
43             /*判断是否为普通文件*/
44             if(S_ISREG(s_buf.st_mode))
45             {
46                 printf("[%s] is a regular file\n",file_path);
47             }
48         }
49     }
50  
51     /*若输入的文件路径是普通文件,则打印并退出程序*/
52     else if(S_ISREG(s_buf.st_mode))
53     {
54         printf("[%s] is a regular file\n",path);
55         return 0;
56     }
57  
58     return 0;
59 }

 

posted @ 2022-07-11 17:13  墨尔基阿德斯  阅读(1552)  评论(0编辑  收藏  举报