From c933b0aff94ecd5335690e2836963db4d9e331f1 Mon Sep 17 00:00:00 2001 From: Michael Drake Date: Thu, 14 Nov 2013 21:01:51 +0000 Subject: Sort non zero-padded numerical filename parts correctly. --- utils/utils.c | 35 +++++++++++++++++++++++++++++++++++ 1 file changed, 35 insertions(+) (limited to 'utils/utils.c') diff --git a/utils/utils.c b/utils/utils.c index 7155ef78d..ac9f5af7a 100644 --- a/utils/utils.c +++ b/utils/utils.c @@ -340,6 +340,41 @@ char *strndup(const char *s, size_t n) #endif +/* Exported interface, documented in utils.c */ +int dir_sort_alpha(const struct dirent **d1, const struct dirent **d2) +{ + const char *s1 = (*d1)->d_name; + const char *s2 = (*d2)->d_name; + + while (*s1 != '\0' && *s2 != '\0') { + if ((*s1 >= '0' && *s1 <= '9') && + (*s2 >= '0' && *s2 <= '9')) { + int n1 = 0, n2 = 0; + while (*s1 >= '0' && *s1 <= '9') { + n1 = n1 * 10 + (*s1) - '0'; + s1++; + } + while (*s2 >= '0' && *s2 <= '9') { + n2 = n2 * 10 + (*s2) - '0'; + s2++; + } + if (n1 != n2) { + return n1 - n2; + } + if (*s1 == '\0' || *s2 == '\0') + break; + } + if (tolower(*s1) != tolower(*s2)) + break; + + s1++; + s2++; + } + + return tolower(*s1) - tolower(*s2); +} + + #ifndef HAVE_SCANDIR int alphasort(const struct dirent **d1, const struct dirent **d2) { -- cgit v1.2.3