--- fsl.c 2003/05/22 14:01:55 1.61
+++ fsl.c 2003/10/10 14:07:49 1.62
@@ -371,6 +371,24 @@
return rc;
}
+/* alphabetically compare one string with another, to use with qsort(3) */
+static int fnamecmp(const void *str1, const void *str2)
+{
+ /* because the end goal is to sort an array of strings in alphabetical */
+ /* decending order, tailor the bahaviour of this compare method to */
+ /* account for null strings that should go at the end of the array */
+ if (*(const char **)str1) {
+ if (*(const char **)str2)
+ return strcmp(*(const char **)str1, *(const char **)str2);
+ else
+ return (-1); /* only str2 was null, so str1 is lesser by default */
+ }
+ else if (*(const char **)str2)
+ return (1); /* only str1 was null, so str2 is lesser by default */
+ else
+ return (0); /* both str1 and str2 were null, so they are equal */
+}
+
/* read all possible files "fsl.*" into buffer */
static fsl_rc_t readallfiles(buf_t *buffer)
{
@@ -380,7 +398,11 @@
char *filename = NULL;
char *cfgdir;
char *prefix;
- int n;
+ char **filearr = NULL;
+ size_t filemem = 0;
+ int filecnt = 0;
+ int fileidx = 0;
+ int n = 0;
if (buffer == NULL)
CU(FSL_ERR_ARG);
@@ -395,21 +417,34 @@
rc = FSL_ERR_ARG;
while ((de = readdir(dp)) != NULL) {
- n = strlen(de->d_name);
- if ( (n >= strlen(prefix))
+ if ( (strlen(de->d_name) >= strlen(prefix))
&& (strncmp(de->d_name, prefix, strlen(prefix)) == 0)) {
- if ((filename = (char *)malloc(strlen(cfgdir) + 1 + n + 1)) == NULL)
+
+ /* prepare to insert a new file string, so make room for one more */
+ if ((filearr = (char **)realloc(filearr, filemem + sizeof(char *))) == NULL)
+ CU(FSL_ERR_MEM);
+ else
+ filemem += sizeof(char *);
+
+ /* allocate for actual filename string from dirent and copy out */
+ n = strlen(cfgdir) + strlen("/") + strlen(de->d_name) + 1;
+ if ((filearr[filecnt] = (char *)malloc(n)) == NULL)
CU(FSL_ERR_MEM);
- filename[0] = '\0';
- strcat(filename, cfgdir);
- strcat(filename, "/");
- strcat(filename, de->d_name);
- if (appendfiletobuffer(buffer, filename) == FSL_OK)
- rc = FSL_OK;
- free(filename);
- filename = NULL;
+ *filearr[filecnt] = '\0';
+ strcat(filearr[filecnt], cfgdir);
+ strcat(filearr[filecnt], "/");
+ strcat(filearr[filecnt], de->d_name);
+ filecnt++;
}
}
+ qsort((void *)filearr, (size_t)filecnt, sizeof(char *), fnamecmp);
+ while (fileidx < filecnt) { /* loop once for every string in sorted array */
+ if (appendfiletobuffer(buffer, filearr[fileidx]) == FSL_OK)
+ rc = FSL_OK;
+ free(filearr[fileidx]);
+ filearr[fileidx] = NULL;
+ fileidx++;
+ }
CU(rc);
CUS:
if (dp != NULL)
|