I plan to use this blog to post codebits that I find myself sending to people over and over again. The first example is how to use a TAILQ from sys/queue.h found on the BSDs. Many Linux distributions also have sys/queue.h but may be missing certain macros such as TAILQ_FOREACH(). At the very least I hope this enticies some newer C programmer to use queue.h rather than rolling their own linked list. I’ll jump directly to the code as I feel it is more or less self explanatory.
The following code can be downloaded here.
tailq_entry { value; TAILQ_ENTRY(tailq_entry) entries; }; TAILQ_HEAD(, tailq_entry) my_tailq_head; main( argc, **argv) { tailq_entry *item; tailq_entry *tmp_item; i; TAILQ_INIT(&my_tailq_head); (i = ; i < ; i++) { item = malloc((*item)); (item == ) { perror(); exit(); } item->value = i; TAILQ_INSERT_TAIL(&my_tailq_head, item, entries); } printf(); TAILQ_FOREACH(item, &my_tailq_head, entries) { printf(, item->value); } printf(); printf(); TAILQ_FOREACH(item, &my_tailq_head, entries) { (item->value == ) { tailq_entry *new_item = malloc((*new_item)); (new_item == ) { perror(); exit(); } new_item->value = ; TAILQ_INSERT_AFTER(&my_tailq_head, item, new_item, entries); ; } } TAILQ_FOREACH(item, &my_tailq_head, entries) { printf(, item->value); } printf(); printf(); (item = TAILQ_FIRST(&my_tailq_head); item != ; item = tmp_item) { tmp_item = TAILQ_NEXT(item, entries); (item->value == ) { TAILQ_REMOVE(&my_tailq_head, item, entries); free(item); ; } } TAILQ_FOREACH(item, &my_tailq_head, entries) { printf(, item->value); } printf(); (item = TAILQ_FIRST(&my_tailq_head)) { TAILQ_REMOVE(&my_tailq_head, item, entries); free(item); } (!TAILQ_EMPTY(&my_tailq_head)) printf(); ; }