How to qsort a dirent in C

我只是一个虾纸丫 提交于 2021-02-11 15:25:56

问题


Brand new to C and finding it confusing. 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).


回答1:


You could store the dirent objects inside an array which you could then pass into qsort. The function cmp should be modified to compare the d_name element inside the dirent pointers. 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;
}


来源:https://stackoverflow.com/questions/55229886/how-to-qsort-a-dirent-in-c

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!