//The Last attempt//
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
struct WordNode {
char word;
int line;
struct WordNode* left;
struct WordNode* right;
};
struct WordNode createNode(char word, int line) {
struct WordNode* node=NULL;
node =malloc(sizeof(struct WordNode));
node->word = word;
node->line = line;
node->left = NULL;
node->right = NULL;
return node;
}
struct WordNode insert(struct WordNode* root, char word, int line) {
if (root==NULL) {
return createNode(word, line);
}
int cmp = strcmp(word, root->word);
if (cmp == 0) {
// word already exists in tree, so do nothing
return root;
} else if (cmp < 0) {
root->left = insert(root->left, word, line);
} else {
root->right = insert(root->right, word, line);
}
return root;
}
int main(int argc, char argv[]) {
if (argc != 2) {
printf("Usage: %s <filename>\n", argv[0]);
return 1;
}
char filename = argv[1];
FILE *file = fopen("D:\TXTFolder\Text1.txt", "r");
if (file == NULL) {
perror("Error opening file");
return 1;
}
struct WordNode *root = NULL;
char line[256];
int lineNumber = 1;
while (fgets(line, sizeof(line), file)) {
char word = strtok(line, " \n\t");
while (word != NULL) {
root = insert(root, word, lineNumber);
word = strtok(NULL, " \n\t");
}
lineNumber++;
}
fclose(file);
return 0;
}
This is a program that reads a text file and stores unique words from that text file in a binary search tree in alphabetical order and this program also stores in that same binary search tree the index of lines in which those stored unique words were mentioned in C.
There seem to have errors in the two functions createNode()
and insert()
because they are both supposed to return a struct but it seems I can't.