C Codes

Load File to Linked List – C

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) {

        fscanf(fp, "%d ", &num);
        start = insert_at_end(start, num);
    return 0;



Let me Know What you Think!

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s