Added new download option to the manual.
[shell-fm.git] / source / strary.c
blob87d32981dc43fa881b15936e694c9d7ff78c1e6a
1 /*
2 Copyright (C) 2006 by Jonas Kramer
3 Copyright (C) 2006 by Bart Trojanowski <bart@jukie.net>
5 Published under the terms of the GNU General Public License (GPL).
6 */
8 #define _GNU_SOURCE
11 #include <stdio.h>
12 #include <stdlib.h>
13 #include <string.h>
14 #include <sys/time.h>
15 #include <sys/types.h>
16 #include <unistd.h>
17 #include <stdarg.h>
18 #include <assert.h>
20 #include "compatibility.h"
21 #include "strary.h"
24 /* Counts the elements of a NULL-terminated array of strings. */
25 unsigned count(char ** list) {
26 unsigned n = 0;
28 if(list != NULL)
29 while(list[n] != NULL)
30 ++n;
32 return n;
35 /* Appends a string to a NULL-terminated array of strings. */
36 char ** append(char ** list, const char * string) {
37 unsigned size = count(list);
39 list = realloc(list, sizeof(char *) * (size + 2));
41 list[size++] = strdup(string);
42 list[size] = NULL;
44 return list;
48 Merge two arrays of strings. If the third parameter is zero,
49 the elements of the second array and the array itself are freed.
51 char ** merge(char ** list, char ** appendix, int keep) {
52 unsigned size = count(list), i;
54 for(i = 0; appendix && appendix[i] != NULL; ++i) {
55 list = realloc(list, sizeof(char *) * (size + 2));
56 list[size++] = strdup(appendix[i]);
57 list[size] = NULL;
59 if(!keep)
60 free(appendix[i]);
63 if(appendix != NULL && !keep)
64 free(appendix);
66 return list;
69 /* Free a NULL-terminated array of strings. */
70 void purge(char ** list) {
71 unsigned i = 0;
73 if(list != NULL) {
74 while(list[i] != NULL)
75 free(list[i++]);
77 free(list);
82 Merge strings of an array to one big string. If the second argument is
83 false, the list is purged.
85 char * join(char ** list, int keep) {
86 unsigned i = 0, length = 0;
87 char * result = NULL;
89 if(list != NULL) {
90 while(list[i] != NULL) {
91 result = realloc(result, sizeof(char) * (length + strlen(list[i]) + 1));
93 strcpy(result + length, list[i]);
94 length += strlen(list[i]);
95 result[length] = 0;
97 ++i;
100 if(!keep)
101 purge(list);
104 return result;