So, I’m doing this customer application where you can create/Modify/Search/List Customers. Later on this expands to linking customers to products with an order and so on, but my focus right now is just on customers. I have created a binary tree and all these functions work, however I need a way to store created customers for another time.
I figured that in some way I would have to transfer all the customers (found in each node) into an array, and then fwrite that array into a file “customer.dat”. have spent a lot of hours on it. here is some code snippets to help better understand what function and structs I have:
typedef struct customer
{
char Name[MAXNAME];
char Surname[MAXNAME];
char ID[MAXID];
char Address[MAXADDRESS];
} Cstmr;
typedef struct node
{
Cstmr item;
struct node * left;
struct node * right;
} Node;
typedef struct tree
{
Node * root;
int size;
} Tree;
the above are structs, Node contains item of type Cstmr and linked left and right nodes. Tree contains a root node and size.
void Traverse (const Tree * ptree, void (* pfun)(Cstmr item))
{
if (ptree != NULL)
InOrder(ptree->root,pfun);
}
static void InOrder(const Node * root, void(* pfun)(Cstmr item))
{
if (root != NULL)
{
InOrder(root->left, pfun);
(*pfun)(root->item);
InOrder(root->right, pfun);
}
}
these functions where used for listing Customers with the addition of the function
void printItem(Cstmr C)
{
printf("%-10s %-10s %-8s\n", C.Name, C.Surname, C.ID);
}
and finally executed by writing
Traverse(tree,printItem);
I tried to alter printItem into another function in order to add to an array (outputting to a file instead of the screen), but now things just got way too complicated! any suggestions?
If it’s not essential that you store your data in an array, you can adapt your
printItemfunction to write directly to a file usingfprintfinstead ofprintf. You will need to also pass a file handle to your function.Your
InOrdertraversal is also a bit buggy. The lineInOrder(root->right, pfun);is never executed as you return immediately above it. Remove only thereturnkeyword. Once you verify yourInOrdertraversal is properly working, try making the proper modifications to have it print to a file (preferably using a function pointer like you do withprintItem).If you actually do want to write to an array, you’ll need to know the total number of items in your tree or use a dynamic container (not available in C, unless you write your own), though you can accomplish what you need without an array.