I have a program (part of an example I am trying to work out), that reads a value from a text file (bus.txt
), and then for these number of seats initializes the values of a structure which is a linked list. All of this is done inside a function, and I want the linked list to be available outside of the function.
Then I want to print out the results, but can't seem to manage to find a solution.
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
int i, j, numberofseats, temp;
char platenr[8], selection;
char firstname[20], lastname[20];
char phone[11];
char* p;
typedef struct psg
{
char fullname[40];
unsigned short phonenr[10];
unsigned int seatnr;
struct psg* next;
} PASSENGERS;
void readfile(char* platenr, int* seatnr, PASSENGERS* passenger, PASSENGERS* tmp, PASSENGERS* start)
{
char buff[60];
FILE* businfo;
businfo = fopen ("bus.txt", "r");
if (businfo == NULL)
{
printf("Error Opening File, check if file bus.txt is present");
exit(1);
}
else
{
fscanf(businfo, "%s %d", platenr, seatnr);
printf("Bus Licence plate Nr is: %s, and Number of Seats is: %d", platenr, *seatnr);
for (i = 0; i < numberofseats; i++)
{
passenger = (PASSENGERS*) malloc (sizeof(PASSENGERS));
if (passenger == NULL)
{
puts("Unable to allocate memory");
exit(1);
}
passenger->next = NULL;
strcpy (passenger->fullname, "A");
passenger->seatnr = i + 1;
for (j = 0; j < 10; j++)
{
passenger->phonenr[j] = 0;
}
if (start == NULL)
{
start = passenger;
}
else
{
tmp = start;
while (tmp->next != NULL)
{
tmp = tmp->next;
}
tmp->next = passenger;
}
}
}
}
int main()
{
PASSENGERS* passenger, *tmp, *start = NULL;
readfile(platenr, &numberofseats, passenger, tmp, start);
PASSENGERS* current = passenger;
while (current != NULL)
{
printf("%s", current->fullname);
printf("\n");
current = current->next;
}
}