NAME
sa_colptr - append an array of pointers to strings from an stralloc into it
SYNOPSIS
#include <limb/samisc.h>
int sa_colptr(stralloc *sa, size_t from, size_t end)
DESCRIPTION
The sa_colptr
() function will scan the content of the given stralloc sa
starting at offset from
, expecting to find a succession of NUL-terminated
strings, up to end
. It will append into sa
an array of pointers to the
strings.
This allows to use said array easily with other functions not stralloc-aware.
This function is merely is wrapper around sa_coloff(3) and sa_off2ptr(3).
RETURN VALUE
Upon successful completion, the sa_colptr
() function returns the number of
strings found, or the number of elements in the array. Otherwise, it returns -1
and sets errno
to indicate the error.
ERRORS
The sa_colptr
() function may fail and set errno
for any of the errors
specified on sa_coloff(3).
EXAMPLE
To get the list of files in the current directory, and sort them using qsort(3), one could do the following (Note the lack of error checking) :
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39
c#include <stdlib.h>
#include <string.h>
#include <limb/output.h>
#include <limb/samisc.h>
#include <limb/stralloc.h>
static int
cmp(const void *p1, const void *p2)
{
const char *s1 = * (const char **) p1;
const char *s2 = * (const char **) p2;
return strcmp(s1, s2);
}
int
main(void)
{
stralloc sa = STRALLOC_ZERO;
/* append the list of all files in the current directory into sa */
sa_ls(&sa, ".", NULL);
/* offset where the array will be stored */
size_t arroff = sa.len;
/* append the array from strings contained within */
int n = sa_colptr(&sa, 0, sa.len);
/* sort the array */
char **arr = (char **) (sa.s + arroff);
qsort(arr, n, sizeof(char *), cmp);
/* show ordered listing */
for (int i = 0; i < n; ++i, ++arr)
out(*arr);
stralloc_free(&sa);
return 0;
}