1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99
| #include<stdio.h>
#include<stdlib.h>
#include<string.h>
#include<dirent.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <unistd.h>
typedef enum
{
FICHIER, REPERTOIRE
}TYPE_FICHIER;
TYPE_FICHIER estRepertoire(const char* nomDuFichier)
{
struct stat statBuff;
stat(nomDuFichier, &statBuff);
if (S_ISDIR(statBuff.st_mode))
return REPERTOIRE;
else
return FICHIER;
}
typedef struct
{
DIR* rep;
char nom[20];
int nombre_elements;
char** elements;
}REP;
REP listerRepertoire (REP repertoireLu)
{
repertoireLu.rep = NULL;
repertoireLu.nombre_elements = 0;
struct dirent* fichierLu = NULL;
char fichierType[15];
int i;
//On ouvre le repertoire
repertoireLu.rep = opendir(repertoireLu.nom);
if (repertoireLu.rep == NULL)
//Message d'erreur d'ouverture
perror("Error");
//premiere lecture afin de determiner le nombre d'elements
i=0;
while ((fichierLu = readdir(repertoireLu.rep)) != NULL)
{
if (strcmp(fichierLu->d_name, ".")!=0 && strcmp(fichierLu->d_name, "..")!=0)
i++;
}
closedir(repertoireLu.rep);
repertoireLu.nombre_elements = i;
printf("%i Fichiers\n",repertoireLu.nombre_elements);
//on alloue un tableau pour stocker les noms de fichiers
repertoireLu.elements = malloc((repertoireLu.nombre_elements +1) * sizeof(char*));
//on relis le repertoire pour stocker les elements dans le tableau
repertoireLu.rep = opendir(repertoireLu.nom);
i=0;
while ((fichierLu = readdir(repertoireLu.rep)) != NULL)
{
if (strcmp(fichierLu->d_name, ".")!=0 && strcmp(fichierLu->d_name, "..")!=0)
{
i++;
if (estRepertoire(fichierLu->d_name) == REPERTOIRE)
strcpy(fichierType, "Dossier");
else strcpy(fichierType, "Fichier");
printf("%i : '%s' %s\n", i, fichierLu->d_name, fichierType);
repertoireLu.elements[i] = malloc(sizeof(fichierLu->d_name + 1)); //LIGNE AJOUTEE
strcpy(repertoireLu.elements[i], fichierLu->d_name);
}
}
return repertoireLu;
}
int main(int argc, char* argv[])
{
REP dossier_courant;
strcpy(dossier_courant.nom, ".");
int i;
//on lit le dossier "."
dossier_courant = listerRepertoire(dossier_courant);
//affichage du tableau
for (i=0; i<dossier_courant.nombre_elements; i++)
printf("%s\n", dossier_courant.elements[i]);
getchar();
//pause
return 0;
} |
Partager