如何在C中对Dirent进行排序 [英] How to qsort a dirent in C

查看:80
本文介绍了如何在C中对Dirent进行排序的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

C的新手,发现它令人困惑.我真正想知道的是,采用两段分开的代码,并使它们一起工作.

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

输出未排序

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

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).

推荐答案

您可以将Dirent对象存储在数组中,然后将其传递给qsort.应该修改功能cmp以比较dirent指针中的d_name元素.像这样

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

这篇关于如何在C中对Dirent进行排序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆