#include #include #include #include #include #include /* On FreeBSD, you can include instead */ #include "arb.h" struct tree_node { int data; ARB16_ENTRY() tree_entry; }; int tncompare(const struct tree_node *a, const struct tree_node *b){ return a->data - b->data; } ARB16_HEAD(int_tree, tree_node) *it; ARB_PROTOTYPE(int_tree, tree_node, tree_entry, tncompare); ARB_GENERATE(int_tree, tree_node, tree_entry, tncompare); struct tree_node *tmp; char contains(int n){ return 0 != ARB_FIND(int_tree, it, (struct tree_node*)&n); } void insert_new(int n){ struct tree_node *nn = ARB_GETFREE(it, tree_entry); nn->data = n; ARB_INSERT(int_tree, it, nn); } #define SIZE 100 int main(int argc, char ** argv){ int fd = open("saved_tree", O_RDWR); if(fd == -1) { printf("Couldn't open saved_tree, trying to create a new one\n"); fd = open("saved_tree", O_RDWR | O_CREAT | O_TRUNC, 0644); char zeros[16] = {0}; for(int i = 0; i < 64; i++) write(fd, zeros, 16); lseek(fd, 0, SEEK_SET); it = mmap(0, 1024, PROT_READ | PROT_WRITE, MAP_SHARED, fd, 0); ARB_INIT(tmp, tree_entry, it, SIZE); } else { it = mmap(0, 1024, PROT_READ | PROT_WRITE, MAP_SHARED, fd, 0); if(it) printf("File opened successfully\n"); else printf("File couldn't be mapped - try removing it\n"); } if(argc > 1) insert_new(atoi(argv[1])); if(contains(5)) puts("The tree contains 5"); else puts("The tree does not contain 5"); if(contains(17)) puts("The tree contains 17"); else puts("The tree does not contain 17"); ARB_FOREACH(tmp, int_tree, it){ printf("%d ", tmp->data); } puts(""); munmap(it, 1024); close(fd); return 0; }