summaryrefslogtreecommitdiff
path: root/utils
diff options
context:
space:
mode:
authorMichael Drake <tlsa@netsurf-browser.org>2013-11-14 21:01:51 +0000
committerMichael Drake <tlsa@netsurf-browser.org>2013-11-14 21:01:51 +0000
commitc933b0aff94ecd5335690e2836963db4d9e331f1 (patch)
tree52b7105607e55460a208876c6af77b0676244c83 /utils
parent5e4e32923d0074647e1db463f931bfc9b69a4f10 (diff)
downloadnetsurf-c933b0aff94ecd5335690e2836963db4d9e331f1.tar.gz
netsurf-c933b0aff94ecd5335690e2836963db4d9e331f1.tar.bz2
Sort non zero-padded numerical filename parts correctly.
Diffstat (limited to 'utils')
-rw-r--r--utils/utils.c35
-rw-r--r--utils/utils.h14
2 files changed, 49 insertions, 0 deletions
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)
{
diff --git a/utils/utils.h b/utils/utils.h
index 8172d2d26..a1ff683d3 100644
--- a/utils/utils.h
+++ b/utils/utils.h
@@ -29,6 +29,8 @@
#include <regex.h>
#include <assert.h>
+struct dirent;
+
#ifndef NOF_ELEMENTS
#define NOF_ELEMENTS(array) (sizeof(array)/sizeof(*(array)))
#endif
@@ -157,6 +159,18 @@ char *human_friendly_bytesize(unsigned long bytesize);
const char *rfc1123_date(time_t t);
unsigned int wallclock(void);
+
+/**
+ * Comparison function for sorting directories.
+ *
+ * Correctly orders non zero-padded numerical parts.
+ * ie. produces "file1, file2, file10" rather than "file1, file10, file2".
+ *
+ * d1 first directory entry
+ * d2 second directory entry
+ */
+int dir_sort_alpha(const struct dirent **d1, const struct dirent **d2);
+
/**
* Return a hex digit for the given numerical value.
*