ryanchai_1995
ryanchai_1995

Reputation: 83

How to scan a file with string line by line and store them into linked list ADT?

I have an assignment asks me to scan a file which have a lot of lines with each line contains one word like this:

sonnets
william
shakespeare
fairest
creatures
...

I need a way to add these words into an array of linked lists created by

LinkedList* data = calloc(50, sizeof(LinkedList));
for (int i = 0; i < 50; i++) {
    data[i] = newLinkedList();
}

I tried using fscanf but the buffer does not actually store the words but erased every time I read a new line. And it ends up with only one words got stored into the list:

raw = fopen("./shakespeare-cleaned5.txt", "r");
char* buf = calloc(50, sizeof(char));
int length = 0;
while (fscanf(raw, "%s", buf) == 1) {
    length = strlen(buf);
    add(data[length], buf);
}
fclose(raw);

Is there any other way to do this?

Here are parts of the linked list ADT:

Node newNode(char* s) {
    Node N = malloc(sizeof(NodeObj));
    N->number = 1;
    N->item = s;
    N->next = NULL;
    return N;
}

void add(LinkedList L, char* s){
    Node N = NULL;
    if( L==NULL ){
        fprintf(stderr, 
            "StringList Error: calling add() on NULL StringList reference\n");
        exit(EXIT_FAILURE);
    }

    int index = find(L, s);

    if(index == 0){
        N = newNode(s);
        N->next = L->head;
        L->head = N;
        (L->numItems)++;
    }else{
        index--;
        N = L->head;
        for (int i = 0; i < index; i++) {
            N = N->next;
        }
        N->number++;
    }
}

I also tried to store all the words into an array but all I got is seg fault.

Upvotes: 0

Views: 66

Answers (1)

ryanchai_1995
ryanchai_1995

Reputation: 83

Solution: Allocate new memory to store the word when creating the Node

char* temp = calloc(50, sizeof(char));
strcpy(temp, s);
N->item = temp;

Upvotes: 2

Related Questions