While using scandir()
it uses alphasort
to sort the list of directory content in reverse order. Now how to print directories in ascending order using scandir()
in c.
.
and ..
must be on top.
Here is the code:
#include<stdio.h>
#include <dirent.h>
#include<string.h>
#include<sys/dir.h>
#include<malloc.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;
}
When you call alphasort
it will sort the entries in ascending order.
In your code you have printed it in reverse order.
To print in ascending order you need to start from index 0
.
For example:
#include<stdio.h>
#include <dirent.h>
#include<string.h>
#include<sys/dir.h>
int main(void)
{
struct dirent **namelist;
int n;
int i=0;
n = scandir(".", &namelist,NULL,alphasort);
if (n < 0)
perror("scandir");
else {
while (i<n) {
printf("%s\n", namelist[i]->d_name);
free(namelist[i]);
++i;
}
free(namelist);
}
return 0;
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With