-1

I have got stuck on this program and feeling very irritated now. It's not showing any error but not giving correct output as well.

Please help me out.

#include<stdio.h>
struct node
{
    int data;
    struct node *link;
};
static int noofnodes=0;
struct node *first=NULL, *last=NULL, *next, *prev, *cur;
void insert1()
{
    FILE *fp;
    int flag=5;
    fp=fopen("./abc.txt","r");
    if(fp == NULL)
    {
            printf("\n not a valid file pointer");
            return;
    }
    printf("EOF has value %d",EOF);
    while(feof(fp)!= EOF )
    {

            cur=(struct node*)malloc(sizeof(struct node));
            fscanf(fp, "%d\n",&cur->data);

            if(first==NULL)
            {
                    first=cur;
                    first->link=NULL;
            }
            else
            {
                    next->link=cur;
            }
            next=cur;
    }
    last=cur;
    fclose(fp);
    printf("Data Inserted from file List_Data.txt");
}

I am calling insert1 from main() to copy the contents of file list_data.txt to my linked list node.
list_data.txt simply contains nos from 1-9 (one number in each line).

Thanks in advance.

Meghan
  • 303
  • 2
  • 6
  • 17

1 Answers1

1

Your I/O loop is wrong, feof() doesn't return EOF.

Don't use feof(), use fscanf() into a temporary variable and stop when it fails. In other words, check that I/O succeeds before relying on the results.

Something like:

int t;

while(fscanf(fp, "%d\n", &t) == 1)
{
  /* allocate new node, set data to t ... */
}

Actually, since whitespace in the format string matches any combination of (including none) whitespace in the input, it's better to put it before the conversion:

while(fscanf(fp, " %d", &t) == 1)
{
}

This works with a general space-separated file of integers, regardless of numbers per line and so on.

Also, please don't cast the return value of malloc() in C.

Community
  • 1
  • 1
unwind
  • 391,730
  • 64
  • 469
  • 606