linux下C语言怎么统计某个目录下的文件个数

已知一个目录,用C语言统计这个目录下有多少个文件

#include <stdio.h>
#include <stdlib.h>
#include <dirent.h>
#include <errno.h>
#include <string.h>

#define MAX 1024

int get_file_count(char *root)
{
DIR *dir;
struct dirent * ptr;
int total = 0;
char path[MAX];
dir = opendir(root); /* 打开目录*/
if(dir == NULL)
{
perror("fail to open dir");
exit(1);
}

errno = 0;
while((ptr = readdir(dir)) != NULL)
{
//顺序读取每一个目录项;
//跳过“..”和“.”两个目录
if(strcmp(ptr->d_name,".") == 0 || strcmp(ptr->d_name,"..") == 0)
{
continue;
}
//printf("%s%s/n",root,ptr->d_name);
//如果是目录,则递归调用 get_file_count函数

if(ptr->d_type == DT_DIR)
{
sprintf(path,"%s%s/",root,ptr->d_name);
//printf("%s/n",path);
total += get_file_count(path);
}

if(ptr->d_type == DT_REG)
{
total++;
printf("%s%s/n",root,ptr->d_name);
}
}
if(errno != 0)
{
printf("fail to read dir"); //失败则输出提示信息
exit(1);
}
closedir(dir);
return total;
}

int main(int argc, char * argv[])
{
int total;
if(argc != 2)
{
printf("wrong usage/n");
exit(1);
}
total = get_file_count(argv[1]);
printf("%s ha %d files/n",argv[1],total);
return 0;
}
温馨提示:答案为网友推荐,仅供参考
第1个回答  2015-07-28
可以用findfirstfile 然后 findnextfile 一个个遍历就行了,遍历num++到结束结果就出来了。我暂时没有更好地方法。
第2个回答  推荐于2017-11-25
你去找一本叫做Unix高级环境编程的书,这里有个链接,第一部分的文件操作方面有关于统计目录下文件数的相关资料的,看这部分的内容比直接给你程序要好本回答被网友采纳
第3个回答  2013-05-28
遍历,判断是文件夹还是文件,++1.
第4个回答  2015-08-14
坐等高人11...

相关了解……

你可能感兴趣的内容

本站内容来自于网友发表,不代表本站立场,仅表示其个人看法,不对其真实性、正确性、有效性作任何的担保
相关事宜请发邮件给我们
© 非常风气网