Welcome to little lamb

Code » limb » master » tree

[master] / src / doc / samisc.h / sa_colptr.3.md

% limb manual
% sa_colptr(3)
% limb 0.1.0
% 2023-07-24

# NAME

sa_colptr - append an array of pointers to strings from an stralloc into it

# SYNOPSIS

    #include <limb/samisc.h>

```pre hl
int sa_colptr(stralloc *<em>sa</em>, size_t <em>from</em>, size_t <em>end</em>)
```

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

! INFO:
! 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) :

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

# SEE ALSO

[sa_coloff](3), [sa_off2ptr](3)