练习:检索一个目录里面有没有bmp文件,如果有把bmp文件名和文件个数打印出来(strstr)
目录文件的个数和普通文件的个数也打印出来
strstr函数功能:能检索到字符串中是否有用户需要的字符串
返回值:如果有返回一个地址指针返回成功;如果没有返回NULL;
char *strstr(const char *haystack, const char *needle);
strstr("hello world", "wor");
参考代码:
#include <dirent.h>
#include <string.h>
#include <errno.h>
/*
*/
int main(int argc,const char **argv)
{
if(argc != 2)
{
printf("请输入路径参数\n");
return -1;
}
DIR *DIR_fp = opendir(argv[1]);//通过主函数调取文件路径
if(DIR_fp == NULL)
{
fprintf(stderr,"open %s error:%s",argv[1],strerror(errno));
return -1;
}
int bmp_num=0,file_num=0,dirfile_num=0;
int i=0;
while(1)
{
struct dirent *dp = readdir(DIR_fp);
if(dp == NULL)//判断是否文件搜索完毕
{
break;
}
char *flag = strstr(dp->d_name,"bmp");//检索bmp文件
if(strcmp(dp->d_name,".")==0 || strcmp(dp->d_name,"..")==0)//跳过两个隐藏文件
{
continue;
}
else if(dp->d_type == DT_REG)//判断普通文件
{
file_num++;
}
else if(dp->d_type == DT_DIR)//判断目录文件
{
dirfile_num++;
}
if(flag == NULL)//判断是否是.bmp文件
{
continue;
}
else
{
printf("文件名:%s\n",dp->d_name);
printf("文件大小:%hu\n",dp->d_reclen);
bmp_num++;
}
}
printf("bmp文件数量:%d\n",bmp_num);
printf("普通文件数量:%d\n",file_num);
printf("目录文件数量:%d\n",dirfile_num);
closedir(DIR_fp);
return 0;
}