In: Computer Science
How to read the given structure from a random CSV file separated by commas(which contains no headers only the values of the contents of the structure) and then insert in a binary search tree using one of the structure contents as a key i.e. datetime and handle duplicates in binary search tree by implementing link_list.Please develop a C code for this.
struct data{
char biker_id[200];
char distance_bike_travelled[200];
char datetime[200];
char count_tripr[200];
}
#include<stdio.h>
#include<stdlib.h>
#include<string.h>
struct node
{
char biker_id[200];
char distance_bike_travelled[200];
char datetime[200];
char count_tripr[200];
struct node* left;
struct node* right;
struct node* next;
};
struct node *root = NULL;
struct node* createNode(char bid[200], char dbt[200], char
dtime[200], char count[200])
{
struct node* newNode = (node*)malloc(sizeof(struct node));
strcpy(newNode->biker_id, bid);
strcpy(newNode->distance_bike_travelled,dbt);
strcpy(newNode->datetime ,dtime);
strcpy(newNode->count_tripr ,count);
newNode->left = NULL;
newNode->right = NULL;
newNode->next = NULL;
return newNode;
}
void createNode1(struct node* root1, char bid[200], char dbt[200],
char dtime[200], char count[200])
{
if(root1->next != NULL)
{
while(root1->next != NULL)
root1=root1->next;
}
struct node* newNode1 = (node*)malloc(sizeof(struct node));
strcpy(newNode1->biker_id, bid);
strcpy(newNode1->distance_bike_travelled,dbt);
strcpy(newNode1->datetime ,dtime);
strcpy(newNode1->count_tripr ,count);
newNode1->next = NULL;
newNode1->left = NULL;
newNode1->right = NULL;
root1->next=newNode1;
}
struct node* insert(struct node* root1, char bid[200], char
dbt[200], char dtime[200], char count[200])
{
if (root1 == NULL) return createNode(bid, dbt, dtime, count);
if (atoi(dtime)<atoi(root1->datetime))
root1->left = insert(root1->left, bid, dbt, dtime,
count);
else if (atoi(dtime)>atoi(root1->datetime))
root1->right = insert(root1->right, bid, dbt, dtime,
count);
else if (atoi(dtime)==atoi(root1->datetime))
createNode1(root1, bid, dbt, dtime, count);
return root;
}
void inorder(struct node *root)
{
if (root != NULL)
{
inorder(root->left);
while(root->next != NULL)
{
printf("%s\t%s\t%s\t%s\n",
root->biker_id,root->distance_bike_travelled,root->datetime,root->count_tripr);
root=root->next;
}
inorder(root->right);
}
}
void read_record()
{
char bid[200];
char dbt[200];
char dtime[200];
char count[200];
FILE *fp;
if ((fp = fopen("filename.csv", "r")) == NULL)
{
printf("Error! opening file");
// Program exits if file pointer returns NULL.
exit(1);
}
while( fscanf(fp, "%s, %s, %s, %s" , &bid, &dbt,
&dtime, &count) != EOF )
{
insert(root, bid, dbt, dtime, count);
}
fclose(fp);
}
int main()
{
read_record();
printf("Bike ID\tDistance Travelled\tDate Time\tCont
trip\n");
inorder(root);
return 0;
}
---------------------------------------------------------------------
Please do comment for any further clarifications..