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)
        else {
                while (n--) {
                        printf("%s\n", namelist[n]->d_name);
        return 0;
 $ gcc -o print_files_in_current_directory print_files_in_current_directory.c 
 $ ./print_files_in_current_directory 
Final Result: Filtering Array of ob... x
Final Result: Filtering Array of objects

Leave a Comment

Sign up to our newsletter!

ADB Commands Android Android Applications Android Build system Application Libraries Application Stack / User Interface Bash / Shell Scripts Bluetooth driver Cloud Technologies Commands and Packages Compilation Content Management System Core Kernel C Programs Development & Build Development, Debugging and Performance Tools Development Environment Setup Django & REST Api Errors & Failures Git Hardware Platforms HTML JAVA Programs Linux, OS Concepts and Networking Linux Device Drivers Linux Host, Ubuntu, SysAdmin Linux Kernel Linux Networking Middleware Libraries, HAL Multimedia NDK / Middleware / HAL Operating System Concepts PHP Programming Languages Scripting and Automation Search Engine Optimisation ( SEO ) Social Media Source Code Management ( SCM ) System Administration, Security Testing and Debugging Uncategorized Web design and development Website Hosting Wordpress Yocto Embedded Linux