Program to load the integer data from file and add them at the end of singly linked list. The file named ‘numbers.txt’ will hold the integer numbers separated by space.
#include <stdio.h> #include <stdlib.h> struct node { int data; struct node *next; }; typedef struct node NODE; NODE * insert_at_end(NODE * start, int data) { NODE * newnode, * nextnode; newnode = (NODE *)malloc(sizeof(NODE)); if(newnode == NULL) { printf("Memory Allocation Failed\n"); return start; } newnode->data = data; newnode->next = NULL; if(start == NULL) start = newnode; else { nextnode = start; while(nextnode->next != NULL) nextnode = nextnode->next; nextnode->next = newnode; } return start; } void display(NODE * start) { printf("The list read from file is...\n"); while(start!=NULL) { printf("%d\t", start->data); start = start->next; } } int main() { FILE *fp; int num; NODE *start = NULL; fp = fopen("numbers.txt", "r"); if(fp == NULL) { printf("Unable to open file\n"); return 0; } while(1) { if(feof(fp)) break; fscanf(fp, "%d ", &num); start = insert_at_end(start, num); } fclose(fp); display(start); return 0; }