Home » Programming Languages » C Programs » C program to print files in current directory in reverse order

C program to print files in current directory in reverse order

The scandir() function scans the directory dirp, calling filter() on each directory entry. Entries for which filter() returns nonzero are stored in strings allocated via malloc(3), sorted using qsort(3) with the comparison function compar(), and collected in array namelist which is allocated via malloc(3). If filter is NULL, all entries are selected.

The alphasort() and versionsort() functions can be used as the comparison function compar(). The former sorts directory entries using strcoll(3), the latter using strverscmp(3) on the strings (*a)->d_name and (*b)->d_name.

 $ vim print_files_in_current_directory.c 
#include <dirent.h>
#include <stdio.h>
#include <stdlib.h>
 
int main(void) {
        struct dirent **namelist;
        int n;
 
        n = scandir(".", &namelist, NULL, alphasort);
        if (n < 0)
                perror("scandir");
        else {
                while (n--) {
                        printf("%s\n", namelist[n]->d_name);
                        free(namelist[n]);
                }
                free(namelist);
        }
        return 0;
}
 $ gcc -o print_files_in_current_directory print_files_in_current_directory.c 
 $ ./print_files_in_current_directory 

Subscribe our Rurban Life YouTube Channel.. "Rural Life, Urban LifeStyle"

Leave a Comment