全新的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]);
}
我确信有更好的方法可以做到这一点,但纯粹出于学术原因,我想使用第一个函数(目录内容)的输出作为最后一个函数的输入(按长度排序)。
您可以将dirent对象存储在一个数组中,然后可以将其传递给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;
}