1 Replies - 283 Views - Last Post: 03 September 2013 - 10:01 AM Rate Topic: -----

#1 S_Madushan  Icon User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 1
  • Joined: 03-September 13

Error reading a file into a linked list - Infinite Loop

Posted 03 September 2013 - 07:56 AM

Hi, all, I am still first year student. So there may be some more errors in my code. If you find them please let me know.

First what is needed to be done is, to read from a file, and add those details into a linked list.
My linked list is :
FILE *studentF;
struct student {
	int cbNo;
	char name[10];
	int age;
	struct student *next;
}*list;


The data has already been saved into a file by a previous run. I need to 'import' those details back to the program next time I run it.
The readFile() function for my program is :
 void readFile () {
	studentF = fopen("studentData.txt","r");
	if (studentF == NULL){
		printf("Error reading student file. Previous data may have been discarded.");
	}
	struct student *tempRead;
	tempRead = (struct student *)malloc(sizeof(struct student));
	while (fread(tempRead,sizeof(struct student),1,studentF) != 0){
		tempRead->next = list;
		list = tempRead;
	}
	fclose(studentF);
}



When I run this code, and view available students, the last read student is shown repeatedly. What I think the problem is, at the last node, list->next doesn't point to NULL. Please can anyone help me in this logic.
I am still allowed to use only C, so no C++.
Thanks.

Is This A Good Question/Topic? 0
  • +

Replies To: Error reading a file into a linked list - Infinite Loop

#2 #define  Icon User is offline

  • Duke of Err
  • member icon

Reputation: 1432
  • View blog
  • Posts: 4,968
  • Joined: 19-February 09

Re: Error reading a file into a linked list - Infinite Loop

Posted 03 September 2013 - 10:01 AM

Hi, for a start you are only allocating one struct in memory - you need one for each record.

If you look at a few reads without a loop we can deduce a few points.
Do you wish to insert at the start of the loop or at the end?
Here considering adding to end of list :

  tempRead = (struct student *) malloc(sizeof(struct student));
  /* list can be set to point to first allocation */

  fread(tempRead,sizeof(struct student), 1, studentF);
  /* set next to result of next malloc call 
     so need to remember previous record address */

  tempRead = (struct student *) malloc(sizeof(struct student));
  /* set next*/

  fread(tempRead,sizeof(struct student), 1, studentF);

  tempRead = (struct student *) malloc(sizeof(struct student));
  /* set next*/

  fread(tempRead,sizeof(struct student), 1, studentF);

  /* at finish set next to NULL? */
  /* since last record will not be used free it? */


Was This Post Helpful? 2
  • +
  • -

Page 1 of 1