I have text file structure like this:
NAME sonMOTHER motherFATHER fatherNAME fatherMOTHER grandmother NAME othersonFATHER otherfatherMOTHER other mother
As output I should get something like this:
grandmother mother --mother and son can be in different orderfathersonothermotherotherfatherotherson
Task is to print family tree in descending order from oldest person in family. Separate different families. Person description always starts with NAME. Program should be written in C . Output can be printed in console or either in new text file.
I tried to write program which takes input from file and create node for each person, also mother and father. Put all nodes in array, and know thinking what should I do next.
Code:
#include <stdio.h>#include <stdlib.h>#include <string.h>#define MAX_LINE_LENGTH 63typedef struct node{ char* name; struct node *mom; //left struct node *dad; //right} t_node;t_node* createNode(char* name) { t_node* newNode = malloc(sizeof(t_node)); if (newNode == NULL) { fprintf(stderr, "Memory allocation failed.\n"); exit(1); } newNode->name = strdup(name); // Allocate memory for the name and copy it newNode->mom = NULL; newNode->dad = NULL; return newNode;}void freeMemory(t_node* nodeArray[], int numNodes){ for (int i = 0; i < numNodes; i++) { free(nodeArray[i]->name); free(nodeArray[i]); }}void printNodes(t_node* nodeArray[], int numNodes){ printf("Nodes created:\n"); for (int i = 0; i < numNodes; i++) { printf("%s\n", nodeArray[i]->name); }}int main() { FILE *fin; char line[MAX_LINE_LENGTH]; char* name; fin = fopen("input.txt", "r"); if(fin == NULL) { printf("Error opening input file.\n"); return 1; } t_node* nodeArray[10000]; // Array to store pointers to created nodes int numNodes = 0; while (fgets(line, MAX_LINE_LENGTH, fin) != NULL) { if (strstr(line, "VARDS")) { name = strstr(line, "NAME") + 6; name[strcspn(name, "\n")] = 0; // Remove newline character // Create a node for the person t_node* person = createNode(name); nodeArray[numNodes++] = person; } else if (strstr(line, "FATHER")) { char* father = strstr(line, "TEVS") + 5; father[strcspn(father, "\n")] = 0; // Create a node for the father if not already created int found = 0; for (int i = 0; i < numNodes; i++) { if (strcmp(nodeArray[i]->name, father) == 0) { found = 1; break; } } if (!found) { t_node* fatherNode = createNode(father); nodeArray[numNodes++] = fatherNode; } } else if (strstr(line, "MOTHER")) { char* mother = strstr(line, "MATE") + 5; mother[strcspn(mother, "\n")] = 0; // Create a node for the mother if not already created int found = 0; for (int i = 0; i < numNodes; i++) { if (strcmp(nodeArray[i]->name, mother) == 0) { found = 1; break; } } if (!found) { t_node* motherNode = createNode(mother); nodeArray[numNodes++] = motherNode; } } //one iteration through 1 person with mother and father } fclose(fin); printNodes(nodeArray, numNodes); freeMemory(nodeArray, numNodes); return 0;}
I Will be grateful for any help.