Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <sys/types.h>
- #include <sys/stat.h>
- #include <stdio.h>
- #include <stdlib.h>
- #include <dirent.h> // opendir, closedir, readdir, struct dirent
- #include <errno.h>
- #include <unistd.h>
- #include <string.h>
- /***** FONCTIONS *****/
- void filetype(const char * dirname, const char * filename) {
- struct stat entry_stat;
- char * path = NULL;
- // nom_dossier + '/' + nom_fichier + '\0'
- path = (char *)malloc(sizeof(char) * (strlen(dirname) + 1 + strlen(filename) + 1));
- strcpy(path, dirname);
- strcat(path, "/");
- strcat(path, filename);
- if(stat(path, &entry_stat) == -1) {
- perror("stat");
- exit(EXIT_FAILURE);
- }
- printf("[");
- if(S_ISDIR(entry_stat.st_mode)) {
- printf("rep.");
- } else if(S_ISREG(entry_stat.st_mode)) {
- printf("fic");
- }
- printf("] ");
- free(path);
- }
- void ls(char * dirname) {
- struct dirent * lecture;
- DIR * rep;
- rep = opendir(dirname);
- if(rep == NULL) {
- printf("Répertoire inexistant\n");
- exit(EXIT_SUCCESS);
- }
- while ((lecture = readdir(rep))) {
- if(lecture == NULL && errno == EBADF) {
- fprintf(stderr, "'%s' is not a directory.\n", dirname);
- return;
- }
- if(strcmp(lecture->d_name, ".") != 0 && strcmp(lecture->d_name, "..") != 0) {
- filetype(dirname, lecture->d_name);
- printf("%s\n", lecture->d_name);
- }
- }
- closedir(rep);
- }
- /***** PROGRAMME PRINCIPAL *****/
- int main(int argc, char * argv[]) {
- char * dirname = ".";
- if(argc > 1) {
- dirname = argv[1];
- }
- ls(dirname);
- return 0;
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement