Parcourir une arborescence avec stat en C

Résolu/Fermé
Camlel Messages postés 1 Date d'inscription mercredi 1 mars 2017 Statut Membre Dernière intervention 1 mars 2017 - Modifié par mamiemando le 22/03/2017 à 09:41
mamiemando Messages postés 33077 Date d'inscription jeudi 12 mai 2005 Statut Modérateur Dernière intervention 18 avril 2024 - 22 mars 2017 à 09:51
Bonjour,
J'ai un problème, je souhaite parcourir une arborescence donné en paramétres et que il me dise si c'est un fichier ou un repertoire (j'utilise stat).
Mais j'ai un problème et je vois vraiment pas ou il est.. je pense c'est a cause de readdir mais je vois pas comment y remedier...
Si quelqu'un peut m'aider ça serait top :D

--------------------
Mon code:

int main(int argc,char *argv[]) {
  DIR *src;
  struct stat ms;
  struct dirent *pt;
  src = ""pendir(argv[1]);;
  while ((pt = readdir(src)) != NULL) {
    if ((stat(pt->d_name,&ms)) == -1) {
      perror("pas bon");
      exit(1);
    }
    if (S_ISREG(ms.st_mode)) {
      printf("%s: fichier regulier \n",pt->d_name);
    }
    if (S_ISDIR(ms.st_mode)) {
      printf("%s: c'est un repertoire \n",pt->d_name);
    }
  }
  return 0;
}

1 réponse

mamiemando Messages postés 33077 Date d'inscription jeudi 12 mai 2005 Statut Modérateur Dernière intervention 18 avril 2024 7 748
Modifié par mamiemando le 22/03/2017 à 09:54
Bonjour

Il suffit de repartir de ces liens :
https://stackoverflow.com/questions/612097/how-can-i-get-the-list-of-files-in-a-directory-using-c-or-c
https://stackoverflow.com/questions/4553012/checking-if-a-file-is-a-directory-or-just-a-file

Exemple :

#include <dirent.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <unistd.h>
#include <stdio.h>
#include <stdlib.h>

int list_directory(const char * dirname) {
    DIR *dir;
    struct dirent *ent;
    struct stat path_stat;

    if ((dir = opendir(dirname)) != NULL) {
        /* Print all the files and directories within directory */
        while ((ent = readdir(dir)) != NULL) {
            const char * path = ent->d_name;
            stat(path, &path_stat);
            if (S_ISREG(path_stat.st_mode)) {
                printf("%s: regular file\n", path);
            } else if (S_ISDIR(path_stat.st_mode)) {
                printf("%s: directory\n", path);
            }
        }
        closedir(dir);
    } else {
        /* Could not open directory */
        perror("Cannot open directory %s", dirname);
        return -1;
    }
    return 0
}

int main() {
    char * dirname = "/home/mando";
    list_directory(dirname);
    return 0;
}


Bonne chance
0