如何在linux C中枚举目录项时忽略子目录

  • 本文关键字:子目录 枚举 linux linux console
  • 更新时间 :
  • 英文 :


我必须忽略子目录项。怎么能做到呢?我想我必须用S_ISDIR(s.st_mode),但我不知道怎么用。你能帮我一下吗?

下面是我的代码:
void recorrer_directorio(char *dir_name) {
    DIR *dir = NULL;
    struct dirent *ent;
    char fich[1024];
    char buff[4096];
    int fd;
    /* OPEN DIRECTORY */
    /*ESTO ES MI CODIGO*/
    dir = opendir(dir_name);
    /* TREATMENT OF ERROR */
    if (dir == NULL) {
        printf("aqui esta mi error");
        perror("Recorrer_Directorio : opendir()");
        exit(1);
    }
    while ((ent = readdir(dir)) != NULL) {
        /* Nos saltamos las que comienzan por un punto "." */
        if (ent->d_name[0] == '.')
            continue;
        /* PATH OF FILE*/
        realpath(ent->d_name, fich);
        printf("MI RUTA COMPLETA DE FCHERO [%s]n", fich);
        /* IGNORE DIRECTORY PATH */
        ..........
    }
}              

如果您的系统支持该文件类型,您可以使用d_type来获取该文件类型:

if (ent->d_type == DT_DIR) {
     /* ent->d_name is a directory. */
}

否则,stat(2)的用法如下:

#include <sys/types.h>
#include <sys/stat.h>
#include <unistd.h>
...
char buf[4096];
snprintf(buf, sizeof buf, "%s/%s", dir_name, ent->d_name);
struct stat sb;
if (stat(buf, &sb) == 0 && S_ISDIR(sb.st_mode)) {
    /* d_name is a directory. */
}

最新更新