c - Generating a Linked List by reading numbers from text file -
i want read in numbers text file , create linked list dynamically, although able it, last node value of 0 added list. how can correct this? should able add value 0 if want not in way.
#include <stdio.h> #include <stdlib.h> typedef struct node { int data; struct node *next; }node; int main(int argc, char const *argv[]) { file *fp = fopen("data.txt", "r"); node *prev = null; while(!feof(fp)){ node *curr = malloc(sizeof(node)); fscanf(fp, "%d", &(curr->data)); fprintf(stdout, "%d-->", curr->data); if(prev != null){ prev->next = curr; } prev = curr; } printf("null\n"); fclose(fp); return 0; }
the input file single column of integers 1 5 2 3 6 4
the output comes this, 0 not part of input 1-->5-->2-->3-->6-->4-->0-->null
following on comment, use of while (!feof(fp))
wrong. if using fscanf
, should check return
(e.g. == 1
) determine success or failure of conversion. should read value temporary value (rather list data) can validate number before assigning list.
putting together, following (note: code reads values filename passed 1st argument (or stdin
) if no argument given)
#include <stdio.h> #include <stdlib.h> typedef struct node { int data; struct node *next; } node; int main (int argc, char **argv) { int tmp = 0; node *prev = null; file *fp = argc > 1 ? fopen (argv[1], "r") : stdin; if (!fp) { /* validate file open reading */ fprintf (stderr, "error: file open failed '%s'.\n", argv[1]); return 1; } while (fscanf (fp, " %d", &tmp) == 1) { /* validate conversion tmp */ node *curr = malloc (sizeof (node)); curr->data = tmp; /* assign tmp curr->data */ fprintf (stdout, "%d-->", curr->data); if (prev != null) { prev->next = curr; } prev = curr; } putchar ('\n'); if (fp != stdin) fclose (fp); /* close if not reading stdin */ return 0; }
additionally, when need '\n'
, don't use printf
, there no need. use putchar ('\n');
look on , let me know if have questions.
Comments
Post a Comment