#include <sys/types.h>
#include <stdio.h>
#include <stdlib.h>
#include <dirent.h>
#include <string.h>
int getFileNum(char* root){
//open
DIR* dir = NULL;
struct dirent* ptr = NULL;
char path[1024] = {0};
int count = 0;
dir = opendir(root);
if(dir == NULL){
perror("opendir");
exit(1);
}
//foreach
while((ptr = readdir(dir)) != NULL){
// . ..
if(strcmp(ptr->d_name,".")==0||strcmp(ptr->d_name,"..")==0){
continue;
}
//dir
if(ptr->d_type == DT_DIR){
//递归子目录
sprintf(path,"%s/%s",root,ptr->d_name);
count += getFileNum(path);
}
//reg
if(ptr->d_type == DT_REG){
count++;
}
}
closedir(dir);
return count;
}
int main(int argc,char* argv[]){
if(argc < 2){
printf("./a.out dir\n");
exit(1);
}
int total = 0;
total = getFileNum(argv[1]);
printf("%s has file numbers :%d\n",argv[1],total);
return 0;
}
查看linux文件目录数 :opendir
于 2022-01-26 21:52:11 首次发布