搜索文件-读目录的使用

#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;
}

 

posted @ 2014-08-25 21:08  米其林轮船  阅读(197)  评论(0编辑  收藏  举报