linux c 遍历目录及文件

#include <dirent.h>
void
recovery_backend() { DIR * pdir ; struct dirent * pdirent; struct stat f_ftime; char full_path[PATH_MAX] = {0}; char buf[PATH_MAX] = {0}; char cmd[256] = {0}; pdir = opendir(cups_backend); if(pdir == NULL) return ; for(pdirent = readdir(pdir);pdirent != NULL;pdirent = readdir(pdir)) { if(strcmp(pdirent->d_name,".")==0||strcmp(pdirent->d_name,"..")==0) continue; memset(full_path,0,sizeof(full_path)); snprintf(full_path,sizeof(full_path),"%s%s",cups_backend,pdirent->d_name); if(stat(full_path,&f_ftime) != 0) if(S_ISDIR(f_ftime.st_mode)) continue; /*子目录跳过*/ if(f_ftime.st_mode & S_IFDIR) continue; memset(buf,0,sizeof(buf)); readlink(full_path,buf,sizeof(buf)); if(strcmp(full_hook_backend,buf) == 0) { remove(full_path); memset(cmd,0,sizeof(cmd)); snprintf(cmd,sizeof(cmd),"cp -P %s%s %s",bk_backend,pdirent->d_name,cups_backend); system(cmd); } } closedir(pdir); }

 

遍历目录

void CConfigfile::GerConfigFile(const char *strpath)
{
    char dir[MAX_PATH] = {0};
    char childpath[MAX_PATH] = {0};
    DIR *dp;                      // 定义子目录流指针
    struct dirent *entry;         // 定义dirent结构指针保存后续目录
    struct stat statbuf;          // 定义statbuf结构保存文件属性
    strcpy(dir, strpath);
    if((dp = opendir(dir)) == NULL) // 打开目录,获取子目录流指针,判断操作是否成功
    {
        puts("can't open dir.");
        return;
    }
    //chdir (dir);                     // 切换到当前目录
    while((entry = readdir(dp)) != NULL)  // 获取下一级目录信息,如果未否则循环
    {
        lstat(entry->d_name, &statbuf); // 获取下一级成员属性
        if(S_IFDIR &statbuf.st_mode)    // 判断下一级成员是否是目录
        {
            if (strcmp(".", entry->d_name) == 0 || strcmp("..", entry->d_name) == 0)
              continue;


            sprintf(childpath,"%s/%s",strpath,entry->d_name);
            printf("path:%s\n",childpath);
            GerConfigFile(childpath);
            //printf("%*s%s/\n", depth, "", entry->d_name);  // 输出目录名称
            //scan_dir(entry->d_name, depth+4);              // 递归调用自身,扫描下一级目录的内容
        }
        else
        {

        }
            //printf("%*s%s\n", depth, "", entry->d_name);  // 输出属性不是目录的成员
    }
    //chdir("..");                                                  // 回到上级目录
    closedir(dp);                                                 // 关闭子目录流
    return;
}

  

posted @ 2017-11-07 15:37  wjbooks  阅读(7059)  评论(0编辑  收藏  举报