#include <sys/stat.h>
#include <dirent.h>
#include <sys/types.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int get_file_num(const char *path);
int main(int argc, char *argv[])
{
if (argc < 2) {
printf("usage: \n\t%s path\n", argv[0]);
return -1;
}
int total_file_num = get_file_num(argv[1]);
printf("普通文件的个数为:%d\n", total_file_num);
return 0;
}
int get_file_num(const char *path)
{
DIR *dir = opendir(path);
if (dir == NULL)
{
perror("opendir");
exit(0);
}
struct dirent *ptr;
int total_file_num = 0;
while ((ptr = readdir(dir)) != NULL)
{
char *d_name = ptr->d_name;
if (strcmp(d_name, ".") == 0 || strcmp(d_name, "..") == 0)
continue;
if (ptr->d_type == DT_DIR)
{
char new_path[256];
sprintf(new_path, "%s/%s", path, d_name);
total_file_num += get_file_num(new_path);
}
if (ptr->d_type == DT_REG)
{
total_file_num++;
}
}
closedir(dir);
return total_file_num;
}
![在这里插入图片描述](https://img-blog.csdnimg.cn/e00603b94232403eb357b1c8e25535a4.png)