save.c ====== /* ================================================================ Program to sort a sequence of positive integers termianted by a negative number. First a binary search sequence tree is constructed then the BSST is traversed in in-order fashion and the sorted list is printed. Also, saves the nodes in binary format on a file. Compile as gcc -ansi inpfile.c -o objfile Prabu 3/15/94 ================================================================ */ #include #define FNAMELEN 15 /* maximum length of the filename */ struct node { int info; struct node *left; /* left child */ struct node *right; /* right child */ }; const int nodesize = sizeof(struct node); /* in bytes */ int getfile(char *message, FILE **fp, char *mode) /* get the file and open it */ { char filename[FNAMELEN + 1]; int i; printf("%s filename : ",message); scanf("%s",filename); if ((*fp = fopen(filename,mode)) == NULL) { printf("can't open %s \n",filename); return(-1); } return(0); } void insert(struct node *p, struct node **r) /* insert node p in the tree */ { if (*r == NULL) *r = p; else if (p -> info < (*r)->info) insert(p, &(*r)->left); else insert(p, &(*r)->right); return; } void inorder(struct node *r) /* print the integers in sorted form */ { if (r != NULL) { inorder(r->left); printf(" %d ", r->info); inorder(r->right); } return; } void preordsave(struct node *r, FILE **f) /* save the node in binary format on the file -- preorder fashion */ { if (r != NULL) { if (!fwrite(r, nodesize, 1, *f)) { printf("Writing to the binary file failed .\n"); exit(1); } if (r->left) preordsave(r->left, f); if (r->right) preordsave(r->right, f); } return; } main() { struct node *root, *p; int n; FILE *fp; root = NULL; printf("Input sequence of integers & terminate by a negative value \n"); scanf("%d", &n); while (n >= 0) { p = (struct node *) malloc(sizeof(struct node)); /* make a new node */ p->info = n; p->left = p->right = NULL; insert(p, &root); scanf("%d", &n); } printf("\nSorted numbers are :\n"); inorder(root); printf("\n\n"); if (getfile("Output",&fp,"wb") < 0) return; preordsave(root, &fp); printf("This binary search sequence tree is saved in the file \n\n"); } Execution ========= Input sequence of integers & terminate by a negative value 45 67 32 58 25 50 60 -4 Sorted numbers are : 25 32 45 50 58 60 67 Output filename : number.bin This binary search sequence tree is saved in the file