Yassine Mrabet
Yassine Mrabet

Reputation: 55

Building a linked list in C

I have a file that contains data in every line. I need to copy each line of strings in each element of a linked list, then print it. But the list isn't printed , maybe the problem is in building the elements of the list.

typedef struct node
{
    char *name;
    struct node *next;
}node;

node *head = NULL;

 node* listall()
{
char temp[50] ;
FILE *f1 = fopen("user_data.txt", "rt");
if(f1 == NULL)
{
            printf("file not found \n");
            return 0;}
//allocate memory for node
    node *ptr = malloc(sizeof(node));
//allocate memory to hold the name
    ptr->name = malloc(1000);

while(fgets(temp,50,f1)!= NULL){
//copy the current name
    strcpy(ptr->name,temp);
    head = ptr->next;
    head->next = NULL;    }
    return head;

}
void list_print(node *head) {
    node *p;
    for (p = head; p != NULL; p = p->next)
        printf("%s", p->name);
    printf("\n");
}

Upvotes: 0

Views: 73

Answers (1)

Adrian Mole
Adrian Mole

Reputation: 51894

Here's an example of how your listall() function could create a list while reading data from the file, based on your code and with annotations that explain what's going on:

node* listall()
{
    char temp[50];
    FILE* f1 = fopen("user_data.txt", "rt");
    if (f1 == NULL)
    {
        printf("file not found \n");
        return NULL;
    }
    node* ptr = NULL; /// Until/unless we find something in the file, we have an empty list!
    node* head = NULL; /// This will be our answer - the START of the list!
    while (fgets(temp, 50, f1) != NULL) {
        node* add = malloc(sizeof(node));
        add->name = malloc(100);
        add->next = NULL; /// This will be the 'new' last node!
        strcpy(add->name, temp); //copy the current name
        if (ptr != NULL) ptr->next = add; /// Append node to end (if list is not empty)
        else head = add; /// This is the first entry, so copy address to our answer.
        ptr = add; /// And keep track of our last (= just created) node.
    }
    fclose(f1); /// Don't forget to close the file when you'e finished with it!
    return head;
}

There are many variations on how to do this, as you will discover with a quick google search.

Upvotes: 0

Related Questions