summaryrefslogtreecommitdiff
path: root/tailq.c
diff options
context:
space:
mode:
Diffstat (limited to 'tailq.c')
-rw-r--r--tailq.c104
1 files changed, 104 insertions, 0 deletions
diff --git a/tailq.c b/tailq.c
new file mode 100644
index 0000000..de9e312
--- /dev/null
+++ b/tailq.c
@@ -0,0 +1,104 @@
+#include <sys/queue.h>
+#include <stdio.h>
+#include <stdlib.h>
+#include <err.h>
+
+/*
+ * tailq 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 tailq element to be referenced by f_link
+ */
+
+struct foo {
+ int f_a;
+ char f_b;
+ TAILQ_ENTRY(foo) f_link;
+};
+
+/*
+ * the head of our tailq of struct foo's (see the manpage for more info)
+ */
+TAILQ_HEAD(tqhead, foo) tq;
+
+struct foo *alloc_foo(int a, char b);
+
+int
+main(void)
+{
+ struct foo *fp, *other;
+ struct tqhead *tqp;
+
+ TAILQ_INIT(&tq);
+ tqp = &tq;
+
+ /*
+ * insert the elements, note the use of the f_link item
+ */
+ fp = alloc_foo(1, 'a');
+ TAILQ_INSERT_HEAD(tqp, fp, f_link);
+
+ fp = alloc_foo(2, 'b');
+ TAILQ_INSERT_TAIL(tqp, fp, f_link);
+
+ /*
+ * put this one after the head of the queue
+ */
+ fp = alloc_foo(3, 'c');
+ TAILQ_INSERT_AFTER(tqp, TAILQ_FIRST(tqp), fp, f_link);
+
+ /*
+ * put this one in front of the one we just inserted
+ */
+ other = alloc_foo(4, 'd');
+ TAILQ_INSERT_BEFORE(fp, other, f_link);
+
+
+ /*
+ * loop through the list
+ */
+ for (fp = TAILQ_FIRST(tqp); fp != NULL; fp = TAILQ_NEXT(fp, f_link))
+ printf("%d %c\n", fp->f_a, fp->f_b);
+
+ /*
+ * loop through the other way, note the use of tqhead
+ */
+ printf("backwards!\n");
+ TAILQ_FOREACH_REVERSE(fp, tqp, f_link, tqhead)
+ printf("%d %c\n", fp->f_a, fp->f_b);
+
+ /*
+ * free up our list
+ */
+ while ((fp = TAILQ_FIRST(tqp)) != NULL) {
+ TAILQ_REMOVE(tqp, fp, f_link);
+ free(fp);
+ }
+
+ /*
+ * make sure
+ */
+ if (TAILQ_EMPTY(tqp))
+ 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);
+}