How to use recursion to traverse folders

    int getFileNum(const char* root)
    {
        int total = 0;
        DIR* dir = null;
        dir = opendir(root);
        if(dir == null)
        {
            perror("opendir error");
            exit(-1);
        }
        
        struct dirent* ptr = null;
        while((ptr = readdir(dir)) != null)
        {
            //不处理 . ..
            if(strcmp(".",ptr->d_name) == 0 || strcmp("..",ptr->d_name) == 0)
            {
                continue;
            }
            
            //判断是不是普通文件
            if(ptr->d_type == DT_TEG)
            {
                total++;
            }
            
            //如果是目录则递归
            if(ptr->p_type == DT_DIR)
            {
                char path[1024] = {0};
                sprintf(path,"%s/%s",root,ptr->d_name);
                total += getFileNum(path);
            }
        }
        
        //关闭目录
        closedir(dir);
        return total;
    }

猜你喜欢

转载自blog.csdn.net/liujun5319/article/details/82009833
今日推荐