您的位置:首页 > 其它

统计一个目录下所有普通文件的个数(包含子目录下的普通文件).

2017-06-12 21:28 274 查看
/*************************************************************************
* File Name: file_cout.c
* Author: lixiaogang
* Function:统计普通文件个数
* Mail: 2412799512@qq.com
* Created Time: 2017年06月12日 星期一 20时59分43秒
************************************************************************/

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

int filesum = 0;

void sys_err(const char *ptr,int num)
{
perror(ptr);
exit(num);
}

void regFile(const char *path)
{
DIR *dir = opendir(path);
if(NULL == dir)
{
sys_err("opendir",-2);
}

while(1)
{
struct dirent *dire = NULL;
dire = readdir(dir);
if(NULL == dire)
{
break;
}

/* 去掉.和.. */
if((strcmp(dire->d_name,".") == 0) || (strcmp(dire->d_name,"..") == 0))
{
continue;
}

/*普通文件,累加计算*/
if(dire->d_type == DT_REG)
{
++filesum;
continue;
}
/*目录文件,继续向下遍历*/
if(dire->d_type == DT_DIR)
{
char buf[1024];
bzero(buf,sizeof(buf));
sprintf(buf,"%s/%s",path,dire->d_name);
regFile(buf);
}
}

closedir(dir);
}

int main(int argc,char *argv[])
{
/* ./a.out  dstfile */
if(argc != 2)
{
printf("Usage: ./a.out dstfil");
exit(-1);
}

const char *path = argv[1];
struct stat st;
int flag = stat(path,&st);
if(flag < 0)
{
sys_err("stat",-1);
}

if(S_ISREG(st.st_mode))
{
++filesum;
return 0;
} else if(S_ISDIR(st.st_mode))
{
regFile(path);
}

printf("filesum = %d\n",filesum);

return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐