summaryrefslogtreecommitdiff
path: root/simpleq.c
diff options
context:
space:
mode:
Diffstat (limited to 'simpleq.c')
-rw-r--r--simpleq.c91
1 files changed, 91 insertions, 0 deletions
diff --git a/simpleq.c b/simpleq.c
new file mode 100644
index 0000000..8c55c73
--- /dev/null
+++ b/simpleq.c
@@ -0,0 +1,91 @@
+#include <sys/queue.h>
+#include <stdio.h>
+#include <stdlib.h>
+#include <err.h>
+
+/*
+ * simpleq 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 simpleq element to be referenced by f_link
+ */
+
+struct foo {
+ int f_a;
+ char f_b;
+ SIMPLEQ_ENTRY(foo) f_link;
+};
+
+/*
+ * the head of our simpleq of struct foo's (see the manpage for more info)
+ */
+SIMPLEQ_HEAD(sqhead, foo) sq;
+
+struct foo *alloc_foo(int a, char b);
+
+int
+main(void)
+{
+ struct foo *fp;
+ struct sqhead *sqp;
+
+ SIMPLEQ_INIT(&sq);
+ sqp = &sq;
+
+ /*
+ * insert the elements, note the use of the f_link item
+ */
+ fp = alloc_foo(1, 'a');
+ SIMPLEQ_INSERT_HEAD(sqp, fp, f_link);
+
+ fp = alloc_foo(2, 'b');
+ SIMPLEQ_INSERT_TAIL(sqp, fp, f_link);
+
+ /*
+ * put this one after the head of the queue
+ */
+ fp = alloc_foo(3, 'c');
+ SIMPLEQ_INSERT_AFTER(sqp, SIMPLEQ_FIRST(sqp), fp, f_link);
+
+
+ /*
+ * loop through the list
+ */
+ for (fp = SIMPLEQ_FIRST(sqp); fp != NULL; fp = SIMPLEQ_NEXT(fp, f_link))
+ printf("%d %c\n", fp->f_a, fp->f_b);
+
+ /*
+ * free up our list
+ */
+ while ((fp = SIMPLEQ_FIRST(sqp)) != NULL) {
+ SIMPLEQ_REMOVE_HEAD(sqp, fp, f_link);
+ free(fp);
+ }
+
+ /*
+ * make sure
+ */
+ if (SIMPLEQ_EMPTY(sqp))
+ 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);
+}