Search code examples
cglib

Assignment when reading line by line from file


GSList* getWordList() {
    GSList *list;
    list = NULL;

    FILE *fh;
    fh = fopen("words.txt", "r");

    char *s;
    size_t len = 0;
    ssize_t read;

    while ((read = getline(&s, &len, fh)) != -1) {
        list = g_slist_append(list,s);
    }
    fclose(fh);
    return list;
}

So I have this code. I know that the issue is that 's' will always equal the last word I read. I'm struggling to figure out the solution for this.

g_s_list_append requires a GPointer passed to it, but I'm changing the value every iteration.

I'm extremely new to C, trying to crash course myself... What I'm thinking is I need to allocate memory for a new char * and set it equal to s and then give that to g_slist_append. Is this correct? Is there a better way to do this?


Solution

  • Assign NULL to s to avoid reading next word into the space previously allocated to s:

    char *s = NULL; // Add initialization
    size_t len = 0;
    ssize_t read;
    
    while ((read = getline(&s, &len, fh)) != -1) {
        list = g_slist_append(list, s);
        s = NULL; // Make sure that s's memory is not reused
    }