Search code examples
clistwhile-loopsingly-linked-listfgetc

Pushing numbers from a text file into a link list


I am trying to push numbers from a text file into a linked list which might have multiple digit numbers in multiple lines. My output is a mess, only printing -47 multiple times. My main doubts are how to read a 2 digit number from the file, although my current code is not even reading any number.

My code:

#include <stdio.h>
#include <stdlib.h>

typedef struct linklist
{
     int data;
     struct linklist *addr;
}ll;

void push(ll **h,int val);
void display(ll **h);


void main()
{
    FILE *fp;
    fp=fopen("re.txt","r");
    char c;
    ll *head=NULL;

    while(c=fgetc(fp)!=EOF)
    {
        if(c==' ' || c=='\n')
        {
            continue;
        } 
        else
        {
            int temp=c-'0';
            printf("Temp = %d",temp);
            push(&head,temp);
        }
    }
    printf("check");
    display(&head);
    fclose(fp);
}

void push(ll **h,int val)
{

    if(*h==NULL)
    {
        ll *temp=(ll*)malloc(sizeof(ll));
        temp->data=val;
        temp->addr=NULL;
        *h=temp;
    }
    else
    {
        ll *current = *h;
        while(current->addr!=NULL)
            current=current->addr;
        current->addr=(ll*)malloc(sizeof(ll));
        current->addr->data=val;
        current->addr->addr=NULL;      
    }
}

void display(ll **h)
{
    ll *current=*h;
    while(current->addr!=NULL)
    {
        printf("%d\t",current->data);
        current=current->addr;
    }
}

Edit:

The re.txt file looks like this:

4
2 1 8 19
6 11 50 89
21 22 47
25 35

Solution

  • Use fscanf which does the work for you.

    You want this:

    int main()
    {
      FILE* fp;
      fp = fopen("re.txt", "r");
      if (fp == NULL)
      {
         printf("Can't open file\n");
         return 1;
      }
      char c;
      ll* head = NULL;
      int temp;
    
      while (fscanf(fp, "%d", &temp) != EOF)
      {
        printf("Temp = %d\n", temp);
        push(&head, temp);
      }
      printf("check");
      display(&head);
      fclose(fp);
    }
    

    There is still room for improvement though.