I want to take the lines of a text file (.txt) and store it with a list (structure that I created). Something in the compilation really makes me perplex and don't have sense for me.
TList* names = initList();
fp = fopen(filename, "r");
if (fp == NULL)
exit(EXIT_FAILURE);
while ((read = getline(&line, &len, fp)) != -1) {
append(names, line);
printf("last -> %s\n", (const char*)names->last->content);
}
printf("%s", (const char*)names->last->content);
This instruction take the line and displays it :
printf("last -> %s\n", (const char*)names->last->content);
but not that one :
printf("%s", (const char*)names->last->content);
I don't understand because nothing have changed between these instructions. Moreover, I have tested the TList structure with char* and it was working.
list.c :
TElement* initElement(const void* content){
TElement* element = (TElement*)malloc(sizeof(TElement));
element->content = content;
element->prev = NULL;
element->next = NULL;
return element;
}
TList* initList(){
TList* list = (TList*)malloc(sizeof(TList));
list->first = NULL;
list->last = NULL;
list->size = 0;
return list;
}
void append(TList* list, const void* content){
TElement* element = initElement(content);
if (list->size == 0){
list->first = element;
list->last = element;
}
else {
list->last->next = element;
element->prev = list->last;
list->last = element;
}
list->size += 1;
}
list.h :
typedef struct TElement{
const void* content;
struct TElement* prev;
struct TElement* next;
} TElement;
typedef struct TList{
int size;
TElement* first;
TElement* last;
} TList;
TElement* initElement(const void* content);
TList* initList();
void append(TList* list, const void* content);