c语言,统计目录下有多少个文件,共计大小、盗墓者是个丑奴儿

//盗墓者是个丑奴儿,原

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <time.h>
#include <ctype.h>
#include <unistd.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <sys/types.h>
#include <dirent.h>
#include <dirent.h>

//函数原型申明

int opend(const char * pathname);
void judge(char * pathname);
char * str(const char * str1,const char * str2);
void readf(const char * pathname);

DIR * dir=NULL;

//opendir打开输入参数的目录,获得指针交给readdir读取目录下的文件

int opend(const char * pathname){
        dir=opendir(pathname);
        if(dir==NULL)
        return -1;
        struct dirent * reado=NULL;
        while((reado=readdir(dir))!=NULL){
                char * tmps=NULL;
                if(reado->d_name[0]=='.')
                continue;
                tmps=str(pathname,reado->d_name);
                if(reado->d_type==DT_DIR){
                        readf(tmps);
                }else{
                        judge(tmps);
                }
                if(reado==NULL)
                free(tmps);
        }
}

//递归打开目录,是目录在自调

void readf(const char * pathname){
        DIR * dir=opendir(pathname);
        struct dirent * reado=NULL;
        while((reado=readdir(dir))!=NULL){
                char * tmps=NULL;
                if(reado->d_name[0]=='.')
                continue;
                tmps=str(pathname,reado->d_name);
                if(reado->d_type==DT_DIR){
                        readf(tmps);
                }else{
                        judge(tmps);
                }
                if(reado==NULL)
                free(tmps);
        }
}

//opend与readf函数都有readdir读取,显然代码重复了,但是在一个函数完成。会存在有一个问题

//存在的问题:即要一直保持着输入的路径参数!又要完成对其他目录的读取。假设传参../那么即要完成对../下的目录读取。又要去读取../中的子目录里面的子目录。opendir就会存在问题。

//我分2个函数读取,opend保持输出的路径目录,只读取输入参数下的目录。如果还有目录路径就自调

//参数:文件路径字符串,stat获得文件信息描述结构体,从文件信息描述结构体buf获得文件大小,并且统计文件个数

//经过str的/[文件路径]反斜线拼接,再调用judge。judge获得文件路径:/目录/目录/文件/。最后的反斜线不能要,stat会因为/认为这下面还有内容!所以第一句代码将最后的反斜线去掉。在获得信息即可。

long count_size=0;
long count_file=0;
void judge(char * pathname){
        pathname[strlen(pathname)-1]='\0';
        struct stat buf={0};
        int i=stat(pathname,&buf);
        if(i==-1)
        exit(0);
        count_file++;
        count_size+=buf.st_size;
}

//路径拼接。如:str1参数../,str2参数test。拼接返回../test/。拼接出绝对路径,方便取得路径去open与read

char * str(const char * str1,const char * str2){
        int size1=strlen(str1);
        int size2=strlen(str2);
        char * arr=(char *)malloc(size1+size2+2);
        memset(arr,'0',size1+size2);
        memcpy(arr,str1,size1);
        memcpy(&(arr[size1]),str2,strlen(str2));
        arr[size1+size2]='/';
        return arr;
}

//main测试

int main(int arg,char ** arv){

        if(arv[1]!=NULL)
        opend(arv[1]);

        printf("File:%ld \n",count_file);
        printf("Size:%ldB \n",count_size);
 

        return 0;

}
 

运行结果:

猜你喜欢

转载自blog.csdn.net/java_dmz/article/details/81173033
今日推荐