summaryrefslogtreecommitdiff
path: root/slist.c
diff options
context:
space:
mode:
authorDimitri Sokolyuk <demon@dim13.org>2008-11-13 16:34:47 +0000
committerDimitri Sokolyuk <demon@dim13.org>2008-11-13 16:34:47 +0000
commit4325c036fca0264d64212c6c837616387818d752 (patch)
tree2e10193e14a1602851a49c2f31cbea9a53971ae0 /slist.c
BSD Lists macros
Diffstat (limited to 'slist.c')
-rw-r--r--slist.c90
1 files changed, 90 insertions, 0 deletions
diff --git a/slist.c b/slist.c
new file mode 100644
index 0000000..e05dd25
--- /dev/null
+++ b/slist.c
@@ -0,0 +1,90 @@
+#include <sys/queue.h>
+#include <stdio.h>
+#include <stdlib.h>
+#include <err.h>
+
+/*
+ * slist macro usage examples by Peter Werner <peterw@ifost.org.au>
+ *
+ * please see http://www.ifost.org.au/~peterw/queue.html for more info
+ */
+
+/*
+ * our struct definition, with the slist element
+ */
+
+struct foo {
+ int f_a;
+ char f_b;
+ SLIST_ENTRY(foo) f_link;
+};
+
+/*
+ * the head of our list of struct foo's (see the manpage for more info)
+ */
+SLIST_HEAD(, foo) list;
+
+struct foo *alloc_foo(int a, char b);
+
+int
+main(void)
+{
+ struct foo *fp;
+
+ SLIST_INIT(&list);
+
+ /*
+ * insert the elements, note the use of the f_link item
+ */
+ fp = alloc_foo(1, 'a');
+ SLIST_INSERT_HEAD(&list, fp, f_link);
+ fp = alloc_foo(2, 'b');
+ SLIST_INSERT_HEAD(&list, fp, f_link);
+ fp = alloc_foo(3, 'c');
+ SLIST_INSERT_HEAD(&list, fp, f_link);
+
+ /*
+ * loop through the list
+ */
+ for (fp = SLIST_FIRST(&list); fp != NULL; fp = SLIST_NEXT(fp, f_link))
+ printf("%d %c\n", fp->f_a, fp->f_b);
+
+ /*
+ * another way of looping
+ */
+ SLIST_FOREACH(fp, &list, f_link)
+ printf("%d %c\n", fp->f_a, fp->f_b);
+
+ /*
+ * free up our list
+ */
+ while (!SLIST_EMPTY(&list)) {
+ fp = SLIST_FIRST(&list);
+ SLIST_REMOVE_HEAD(&list, f_link);
+ free(fp);
+ }
+
+ /*
+ * make sure
+ */
+ if (SLIST_EMPTY(&list))
+ printf("List is empty!\n");
+ else
+ printf("List not empty!\n");
+
+ return(0);
+}
+
+struct foo *
+alloc_foo(int a, char b)
+{
+ struct foo *tmp;
+
+ tmp = (struct foo *)malloc(sizeof(struct foo));
+ if (tmp == NULL)
+ err(1, "malloc");
+
+ tmp->f_a = a;
+ tmp->f_b = b;
+ return(tmp);
+}