linux下的普通文件的递归统计

xiaoxiao2021-02-28  55

代码如下   1 #include<stdio.h>   2 #include<stdlib.h>   3 #include<sys/types.h>   4 #include<dirent.h>   5 int getFileNum(char *root){//得到文件的数量 传入一个字符串   6         DIR* dir=NULL;//初始化目录   7         int total=0;//初始化计数器   8         dir=opendir(root);//打开目录下的文件   9         if(dir==NULL){//目录为空  10         perror("Open");//打印出错误信息  11         exit(1);//退出程序  12         }  13         struct dirent *ptr=NULL;//定义一个结构体指针  14         char path[1024]={0};//初始化路径  15         while((ptr=(readdir(dir)))!=NULL){//遍历当前的目录  16         //过滤掉一些不和逻辑的  17         if(strcmp(ptr->d_name,".")==0||strcmp(ptr->d_name,"..")==0){  18         continue;//继续  19         }  20         if(ptr->d_type==DT_DIR){  21         //递归读目录  22         //拼路径  23         sprintf(path,"%s/%s",root,ptr->d_name);  24         total+=getFileNum(path);//计算总和  25         }  26         //如果是普通文件的话  27         if(ptr->d_type==DT_REG){  28         total++;//计数器加一  29         }  30         }  31         closedir(dir);//关闭目录  32         return total;  33 }  34   35 int main(){  36         int total= getFileNum("heh");//得到总数  37         printf("The number is %d",total);  38 }

转载请注明原文地址: https://www.6miu.com/read-58719.html

最新回复(0)