首页 > 代码库 > 搜索文件-读目录的使用

搜索文件-读目录的使用

#include<stdio.h>#include<sys/stat.h>#include<string.h>#include<errno.h>#include<stdlib.h>#include<dirent.h>void err_sys(const char *s){    printf("%s error:%s\n",s,strerror(errno));    exit(0);}bool isFind(char *pathname,char *filename){    return (strstr(pathname,filename)!=NULL);}void mySearch(char *pathname,char *filename){    if(isFind(pathname,filename))    {        printf("%s\n",pathname);    }    struct stat mystat;    if(lstat(pathname,&mystat)<0)    {        err_sys("lstat");    }    if(S_ISDIR(mystat.st_mode))    {        DIR *dp;        struct dirent *pdir;        char temp[256]="";        if((dp = opendir(pathname))==NULL)        {            printf("can‘t read %s\n",pathname);            return;        }        while((pdir=readdir(dp))!=NULL)        {            if(strcmp(pdir->d_name,".")==0 || strcmp(pdir->d_name,"..")==0)            {                continue;            }            if(strcmp(pathname,"/")==0)            {                sprintf(temp,"%s%s",pathname,pdir->d_name);            }            else            {                sprintf(temp,"%s/%s",pathname,pdir->d_name);            }            mySearch(temp,filename);            memset(temp,0,sizeof(temp));        }    }}int main(int argc,char *argv[]){    mySearch(argv[1],argv[2]);    return 0;}

 

搜索文件-读目录的使用