gpt4 book ai didi

c - 在 c 中使用 scandir() 按升序打印目录

转载 作者:太空狗 更新时间:2023-10-29 15:24:07 25 4
gpt4 key购买 nike

在使用 scandir() 时,它使用 alphasort 以相反的顺序对目录内容列表进行排序。现在如何在 c 中使用 scandir() 按升序打印目录。

... 必须在最上面。

代码如下:


#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;
}

最佳答案

当您调用 alphasort 时,它将按升序对条目进行排序。

在您的代码中,您以相反的顺序打印了它。

要按升序打印,您需要从索引 0 开始。


例如:

#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;
}

关于c - 在 c 中使用 scandir() 按升序打印目录,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26552503/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com