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 Application Stack / User Interface Bash / Shell Scripts Commands and Packages Compilation Content Management System - CMS Core Kernel C Programs Development & Build Development Environment Setup Errors & Failures Flutter git Go Language Programs Hardware Platforms HTML JAVA Programs Kernel & Device Drivers Linux, OS Concepts and Networking Linux Device Drivers Linux Host, Ubuntu, SysAdmin Linux Kernel Linux Networking Middleware Libraries, HAL Monetization / Google AdSense NDK / Middleware / HAL OS Concepts PHP Programming Languages RaspberryPi Scripting and Automation Search Engine Optimisation ( SEO ) Social Media Socurce Code Management ( SCM ) System Administration, Security Testing and Debugging Uncategorized User Interface Userspace Utilities Web design and development Wordpress Yocto / Bitbake / Openembedded

Leave a Reply / Ask Question