I have created a linked list
, now I am trying to read data in from a file however every time a new entry is read and assigned to the structure the first node is reassigned and removes the data from the previous entry. I would like to find out why my code is doing this.
/* read file containing database of employees */
static void read_employee_database(char *file_name)
{
char Name[MAX_NAME_LENGTH] = "\0";
int Age;
char Sex;
char Job[MAX_JOB_LENGTH] = "\0";
char ptr[10];
char temp[100];
int test = 0, count = 0;
/*assigns enough memory*/
Employee *pNewStruct = (Employee *)malloc(sizeof(Employee));
FILE *pFile;
pFile = fopen(file_name, "r");
while (feof(pFile) == 0) {
fprintf(stderr, "\nFirst node name %s\n\n", pFirstNode->name);
read_string(pFile, "Name: ", Name, MAX_NAME_LENGTH);
strcpy(pNewStruct->name, Name);
read_string(pFile, "Sex: ", temp, 4);
Sex = temp[0];
pNewStruct->sex = Sex;
read_string(pFile, "Age: ", temp, 100);
Age = atoi(temp);
pNewStruct->age = Age;
read_string(pFile, "Job: ", Job, MAX_JOB_LENGTH);
strcpy(pNewStruct->job, Job);
fprintf(stderr, "The name is: %s \n", Name);
fprintf(stderr, "The Age is: %i \n", Age);
fprintf(stderr, "The Sex is: %c \n", Sex);
fprintf(stderr, "The Job is: %s \n", Job);
fprintf(stderr, "\n");
fgetc(pFile);
/*Test all data for given entry*/
test = checkName(&pNewStruct->name);
if (test == 0) {
fprintf(stderr, "Name is issue");
exit(-1);
}
else if (pNewStruct->sex != 'M' && pNewStruct->sex != 'F') {
fprintf(stderr, "Sex is issue");
exit(-1);
}
else if (pNewStruct->age <= 0) {
fprintf(stderr, "Age is issue");
exit(-1);
}
else if (strlen(pNewStruct->job) == 0) {
fprintf(stderr, "Job is issue");
exit(-1);
}
else {
if (pFirstNode->name == NULL) {
fprintf(stderr, "a new node is created\n\n");
pNewStruct->next = NULL;
pNewStruct->prev = NULL;
pFirstNode = pNewStruct;
}
else {
fprintf(stderr, "Else statement run\n\n");
}
}
}
fclose(pFile);
}
At this point in the code I only expect that the first node will be assigned given "pFirstNode
" is a public variable
that is NULL
. However the newest entry that is read in automatically is set as pFirstNode
even though the if
statement condition is not met.
The Actual output:
First node name (null)
The name is: Graham, Billy
The Age is: 63
The Sex is: M
The Job is: Evangelist
a new node is created
First node name Graham, Billy
The name is: Karula, Roger
The Age is: 23
The Sex is: M
The Job is: Engineer
Else statement run
First node name Karula, Roger
The name is: Smart, Lisa
The Age is: 18
The Sex is: F
The Job is: Trainee engineer
Else statement run
I am using Ubuntu if that is important.