-
Link List output
what's wrong with this code trying to rad from a file using link list ....
the output is something like this
787878789898988
6
6456
56
56
56
56
56
something that is not on the txt file.
void traverse (void);
/* Structure for printing the id.txt file */
struct id_card
{
int ID;
struct id_card *nextptr;
};
typedef struct id_card node;
void traverse (void)
{
FILE *fp;
node list1;
node *newptr, *currptr, *prevptr;
int NUM, i, ch ,j=0;
int NUM_2 = 6;
newptr= (node*)malloc(sizeof(node));
fp = fopen("id.txt","r");
if (fp == NULL)
{
printf("Unabale to open id.txt file \n");
exit(1);
}
currptr = newptr;
for ( i = 1; i<=8; i++)
{
NUM = getc(fp);
NUM = NUM-48;
newptr->ID = NUM;
printf ("%d",NUM);
newptr->nextptr=(node*)malloc(sizeof(node));
newptr=newptr->nextptr;
}
if(newptr !=NULL){
newptr->ID = NUM_2;
newptr->nextptr=currptr;
currptr=newptr;
}
else
{
printf("\n %d not inserted. No memory available.\n",NUM_2);
}
do{
j++;
printf("\n");
printf("%d", currptr->ID);
currptr=currptr->nextptr;
}
while(j<=8);
fclose(fp);
}
pls help !!!
-
Code:
#include <stdio.h>
#include <stdlib.h>
void traverse(void);
/* Structure for printing the id.txt file */
struct id_card {
int ID;
struct id_card *nextptr;
};
typedef struct id_card node;
void traverse(void) {
FILE *fp;
node *newptr = NULL, *currptr = NULL;
int NUM, i, j=0;
int NUM_2 = 6;
newptr= (node*)malloc( sizeof(node) );
fp = fopen( "id.txt","r" );
if(fp == NULL) {
printf( "Unabale to open id.txt file \n" );
exit( 1 );
}
currptr = newptr;
for(i = 1; i<=8; i++) {
NUM = getc( fp );
NUM = NUM-48;
/*!! this is the problem - newptr isn't pointing at a valid node */
/*!! so trying to dereference it is a bad idea */
/*!! you've got to malloc a node before trying to store data in it */
newptr->ID = NUM;
printf( "%d",NUM );
newptr->nextptr=malloc( sizeof(node) );
newptr=newptr->nextptr;
}
if(newptr != NULL) {
newptr->ID = NUM_2;
newptr->nextptr=currptr;
currptr=newptr;
} else {
printf( "\n %d not inserted. No memory available.\n",NUM_2 );
}
do {
j++;
printf( "\n" );
printf( "%d", currptr->ID );
currptr=currptr->nextptr;
}
while(j<=8);
fclose( fp );
}
-
Do you have any suggestion on how i can do that ?