I'm writing a program that takes info from a file and adds it to a linked list then and a function that adds info to the linked list. My problem is that when I call addContact()
after openBook()
the program crashes, but calling each of them separately works fine.
I can't find the problem.
openBook()
: opens a file, reads data from file to a linkedList
addContact()
: takes info, saves data to linkedList
#include <stdio.h>
typedef struct node {
char name[50];
char email[50];
char ad[200];
char phone[11];
struct node *next;
} NODE;
NODE *head = NULL;
void openBook()
{
FILE *read = fopen("Book.txt", "r");
if (read == NULL)
{
return;
}
NODE *ite = NULL;
char name[50] = "", email[50] = "", ad[200] = "", phone[11] = "";
if (!feof(read))
{
head = (NODE*)malloc(sizeof(NODE));
fscanf(read, "%s%s%s%s", head->name, head->email, head->ad, head->phone);
}
ite = head;
while (!feof(read))
{
ite->next = (NODE*)malloc(sizeof(NODE));
ite = ite->next;
fscanf(read, "%s%s%s%s", ite->name, ite->email, ite->ad, ite->phone);
}
ite->next = NULL;
fclose(read);
}
void addContact()
{
NODE *ite = head;
if (head != NULL)
{
while (ite->next!=NULL)
ite = ite->next;
ite->next = (NODE*)malloc(sizeof(NODE*));
ite = ite->next;
}
else
{
head = (NODE*)malloc(sizeof(NODE*));
ite = head;
}
fflush(stdin);
printf("Enter name (no space): ");
scanf("%s", ite->name);
fflush(stdin);
printf("Enter email : ");
scanf("%s", ite->email);
fflush(stdin);
printf("Enter address : ");
scanf("%s", ite->ad);
fflush(stdin);
printf("Enter phone : ");
scanf("%s", ite->phone);
fflush(stdin);
ite->next = NULL;
}
void printList()
{
NODE *iterator;
int i;
iterator = head;
while (iterator != NULL)
{
printf("%s\n", iterator->name);
iterator = iterator->next;
}
}
int main()
{
openBook();
addContact();
printList();
return 0;
}
It's amazing the following works :
int main()
{
addContact();
printList();
return 0;
}
but the following crashes :
int main()
{
FILE *read = fopen("Book.txt", "r");
fclose(read);
addContact();
printList();
return 0;
}