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
fgetswhich only read characters but usefscanf. Also edit and show the first 3-4 lines ofre.txt.lorll. My first thought was "what are those elevens doing". Worse for an r-value. You shouldn't have to peer at code or mistake a variable for a number.while(c=fgetc(fp)!=EOF)is missing a critical set of parentheses. It should bewhile( (c=fgetc(fp)) != EOF)fp=fopen("re.txt","r");a function call (likefopen()) can fail. Always check (!=NULL) the returned value to assure the operation was successful. If not successful (==NULL) then callperror( "fopen failed" )to output both your error message and the text reason the system thinks the error occurred tostderrso the user is informed of the problem. Generally, this is a unrecoverable error, so clean up then callexit( EXIT_FAILURE );