guille guille - 1 month ago 9
C Question

How to ignore subdirectories when enumerating directory entries in linux C

I must ignore entries that are subdirectories. How can do that? I think I have to use

S_ISDIR(s.st_mode)
but I don't know how. Can you help me please?

Here is my code:

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 */
..........
}
}

Answer

You can use d_type to get the file type if it's supported on your system:

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

Otherwise, you can use stat(2) as follows:

#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. */
}
Comments