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 
Android Android Commands Android Java Applications Application Libraries Bash / Shell Scripts Bluetooth driver Build Frameworks Commands and Packages Core Kernel C Programs Development Environment Setup Documents / Books Errors & Failures File Systems Framebuffer / Display Driver git Go Language Programs Hardware Platforms Home JAVA Programs Kernel & Device Drivers Kernel Booting and Porting Linux, OS Concepts and Networking Linux Device Drivers Linux Host, Ubuntu, SysAdmin Linux Kernel Linux Networking Middleware Libraries, HAL NDK / Middleware / HAL Network Driver OS Concepts PHP Procfs Filesystem Programming Languages RaspberryPi Scripting and Automation Search Engine Optimisation ( SEO ) Socurce Code Management ( SCM ) System Administration, Security Testing and Debugging Uncategorized Userspace Utilities Web design and development Wordpress Yocto / Bitbake / Openembedded

Leave a Reply