gaddag* parse_gaddag(const char* filename) { // Instantiate the root GADDAG gaddag* root_gaddag = create_gaddag(); // Open the input file handle FILE* fp = fopen(filename, "r"); if (fp == 0) { fprintf(stderr, "Filename %s is invalid. Please try again.\n", filename); } char* linebuf = (char*) malloc(LONGEST_LINE_LENGTH * sizeof(char)); memset(linebuf, 0, LONGEST_LINE_LENGTH); // For each line while (fscanf(fp, "%s", linebuf) != EOF) { // prepare it (uppercase + strip), format_string_for_gaddag(linebuf); // split into representations. char* representations = split_into_representations(linebuf); // add to the Gaddag add_to_gaddag(root_gaddag, linebuf, representations); memset(linebuf, 0, LONGEST_LINE_LENGTH); free(representations); } free(linebuf); fclose(fp); return root_gaddag; }
void add_to_gaddag(gaddag* root, const char* str, const char* representations) { const unsigned length = strlen(str); const unsigned rep_length = length + 1; gaddag* working_gaddag = root; unsigned row, col; for (row = 0; row < length; ++row) { for (col = 0; col < rep_length; ++col) { const unsigned index = (row * rep_length) + col; const char key = representations[index]; unsigned offset = offset_from_key(key); gaddag* branch = working_gaddag->ptrs[offset]; if (!branch) { // If the key isn't present, create a new node. gaddag* new_node = create_gaddag(); // Link it to this one. *(working_gaddag->ptrs + offset) = new_node; // set this to the working gaddag, and continue the loop. working_gaddag = new_node; } else { // If the key exists. // trace it, continue the loop. working_gaddag = branch; } } set_terminator(working_gaddag); working_gaddag = root; } }