gpt4 book ai didi

c - 如何在 C 中对 dirent 进行 qsort

转载 作者:行者123 更新时间:2023-11-30 16:20:38 26 4
gpt4 key购买 nike

对于 C 语言来说是全新的,并且发现它令人困惑。我真正想知道的是采用两段独立的代码并使它们一起工作。

<小时/>

下面是一些简单列出当前目录内容的代码:

#include <stdio.h>
#include <sys/types.h>
#include <dirent.h>

int
main (void)
{
DIR *dp;
struct dirent *ep;

dp = opendir ("./");
if (dp != NULL)
{
while (ep = readdir (dp))
puts (ep->d_name);
(void) closedir (dp);
}
else
perror ("Couldn't open the directory");

return 0;
}

输出未排序

<小时/>

下面是一些使用快速排序算法按元素长度对数组进行排序的代码:

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

char *array[] = { "XX", "YYY", "Z" };
#define N (sizeof(array) / sizeof(array[0]))

int
cmp(const void *a, const void *b)
{
size_t lena = strlen(*(const char **)a);
size_t lenb = strlen(*(const char **)b);
return lena < lenb ? -1 : lena > lenb;
}

int
main()
{
size_t i;
qsort(array, N, sizeof(array[0]), cmp);
for (i = 0; i < N; i++)
printf("%s\n", array[i]);
}
<小时/>

我确信有更好的方法可以做到这一点,但出于纯粹的学术原因,我想使用第一个函数的输出(目录内容)作为最后一个函数的输入(按长度排序)。

最佳答案

您可以将不同的对象存储在一个数组中,然后将其传递给 qsort。 应修改函数 cmp 以比较 dirent 指针内的 d_name 元素。像这样

int cmp(const *a, const void *b)
{
size_t lena = strlen(((struct dirent *) a)->d_name);
size_t lenb = strlen(((struct dirent *) b)->d_name);
return lena < lenb ? -1 : lena > lenb;
}

关于c - 如何在 C 中对 dirent 进行 qsort,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55229886/

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