I'm just learning about linked lists and I have to do an assignment that has many parts, but I'm starting out and the very first thing I need to do is read in an input file into a linked list. Part of the file is:
George Washington, 2345678
John Adams, 3456789
Thomas Jefferson, 4567890
James Madison, 0987654
James Monroe, 9876543
John Quincy Adams, 8765432
and contains a total of 26 lines.
All I want to do now is simply read in the file. I try by using this code (in main for now)
#include <stdio.h>
#include <stdlib.h>
struct node{
char name[20];
int id;
struct node *next;
}*head;
int main(void){
struct node *temp;
temp = (struct node *)malloc(sizeof(struct node));
head = temp;
FILE *ifp;
ifp = fopen("AssignmentOneInput.txt", "r");
int c = 0;
while(c<26){
fscanf(ifp, "%s", &temp->name);
fscanf(ifp, "%d", &temp->id);
printf("%d\n", c);
temp = temp->next;
c++;
}
For the output, I know that the first name and the first ID are scanned in, because the value of c is displayed as 0 (right now I'm arbitrarily using the value of c to control the fscanf). But after that, the program crashes. So the problem must be with temp = temp->next;
It compiles fine.
I am very new to linked lists, so I really don't know what I'm doing.
Your help is appreciated!