#define _POSIX_C_SOURCE 1 #include #include #include #include #include #include #include #include #define LONGUEUR_MAX_LIGNE 60 static option_recursif = 0; static option_repertoire = 0; static option_fichier = 0; static void usage(char *cmd); static void lsg(char *nom); static char *faire_nom(char *prefixe, char *nom); static void afficher(char *nom); int main(int argc, char *argv[]) { int i = 1; while (i < argc) { if (strcmp(argv[i], "-R") == 0) option_recursif = 1; else if (strcmp(argv[i], "-r") == 0) option_repertoire = 1; else if (strcmp(argv[i], "-f") == 0) option_fichier = 1; else if (strcmp(argv[i], "--") == 0) { i++; break; } else if (argv[0][0] == '-') usage(argv[0]); else break; i++; } if (option_fichier == 0 && option_repertoire == 0) option_fichier = 1; if (i == argc) lsg("."); else while (i < argc) { lsg(argv[i]); i++; } printf("\n"); return EXIT_SUCCESS; } static void usage(char *cmd) { fprintf(stderr, "Usage: %s [-r] [-f] [-R] [«chemin»...]\n", cmd); exit(EXIT_FAILURE); } static void lsg(char *nom) { struct stat caracteristiques; if (stat(nom, &caracteristiques) == -1) { perror(nom); return; } if (S_ISDIR(caracteristiques.st_mode)) { if (option_repertoire) afficher(nom); if (option_recursif) { DIR *flot = opendir(nom); if (flot == NULL) { perror(nom); return; } for (;;) { struct dirent *entree; char *nouveau_nom; errno = 0; entree = readdir(flot); if (entree == NULL) { if (errno != 0) perror(nom); closedir(flot); break; } if (strcmp(entree->d_name, ".") == 0 || strcmp(entree->d_name, "..") == 0) continue; nouveau_nom = faire_nom(nom, entree->d_name); lsg(nouveau_nom); free(nouveau_nom); } } } else if (option_fichier) afficher(nom); } static char *faire_nom(char *prefixe, char *nom) { if (*prefixe == '\0') return strcpy(malloc(strlen(nom) + 1), nom); else { char *s = malloc(strlen(prefixe) + strlen(nom) + 2); sprintf(s, "%s/%s", prefixe, nom); return s; } } static void afficher(char *nom) { static longueur_courante = 0; int longueur_nom = strlen(nom); if (longueur_courante + longueur_nom >= LONGUEUR_MAX_LIGNE) { longueur_courante = 0; printf("\n"); } printf("%s ", nom); longueur_courante += longueur_nom; }