简体   繁体   English

如何在C中对Dirent进行排序

[英]How to qsort a dirent in C

Brand new to C and finding it confusing. 刚接触C并感到困惑。 What I really want to know about, is taking two separate pieces of code and getting them to work together. 我真正想知道的是,编写两个单独的代码并将它们一起使用。


Here's some code that simply lists the contents of the current directory: 以下是一些简单列出当前目录内容的代码:

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

The output is unsorted 输出未排序


Here's some code that sorts an array by length of elements, using a quick sort algorithm: 这是一些使用快速排序算法按元素长度对数组进行排序的代码:

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

I'm sure there are better ways to do this, but for purely academic reasons, I'd like to use the output of the first function (directory contents) as an input to the last function (sort by length). 我确定有更好的方法来执行此操作,但是出于纯粹的学术原因,我想将第一个函数的输出(目录内容)用作最后一个函数的输入(按长度排序)。

You could store the dirent objects inside an array which you could then pass into qsort. 您可以将Dirent对象存储在数组中,然后将其传递给qsort。 The function cmp should be modified to compare the d_name element inside the dirent pointers. 应该修改功能cmp以比较dirent指针中的d_name元素。 like so 像这样

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM