Krishna Sailesh
Krishna Sailesh

Reputation: 185

scanning file contents into a linked list

I have a file which contains the information of employees(Name and their ID) of a company. Sample file:

Sailesh 160031158
John 160031145
Sam 160031499

I need to scan these contents into a linked list. If I know the number of employees(say 'x') present in the file, I can store them in a linked list using following code snippet:

struct node
{
    int id;
    char name[100];
    struct node *next;
}*start=NULL,*new,*prev;

void scan()
{
    fp=fopen("employee_info.c","r");
    for(i=0;i<x;i++)
    { 
        if(start==NULL)
        {
            new=(struct node *)malloc(sizeof(struct node));
            start=new;
            fscanf(fp,"%s%d",new->name,&new->id);
            new->next=NULL;
            prev=new;
        }
        else
        {
            new=(struct node *)malloc(sizeof(struct node));
            fscanf(fp,"%s%d",new->name,&new->id);
            new->next=NULL;
            prev->next=new;
            prev=new;
        }
    }
}

But the problem is that I should be able to scan the details in the file into the linked list without knowing the no. of employees present('x').

Upvotes: 0

Views: 185

Answers (1)

Ben Wainwright
Ben Wainwright

Reputation: 4651

From the C documentation, the method fscanf() has the following return value

On success, the function returns the number of items of the argument list successfully filled. This count can match the expected number of items or be less (even zero) due to a matching failure, a reading error, or the reach of the end-of-file.

If a reading error happens or the end-of-file is reached while reading, the proper indicator is set (feof or ferror). And, if either happens before any data could be successfully read, EOF is returned.

So rather than your for loop, try putting the result of fscanf into a while loop and testing for the EOF return value. Something like this:

while(fscanf(fp,"%s%d", new->name, &new->id) != EOF) {
    // Do something
}

Upvotes: 2

Related Questions