Hi,

I am writing a program at the moment which requires me to scan in data from an external file, which to be added to a linked list. The external file is a list of pairs of cities and the distances between them - each piece of data is tab-delimited, and each pair of cities is on a new line. Each node within the linked list should contain the name of city one, the name of city two, and the distance between them. My code so far is shown below:

typedef struct node_pair_info	// declare structure for npi database
{
	char city1[20];
	char city2[20];
	int distance;
	struct node_pair_info *next;
} NPI;

NPI *add_nodes(NPI * item)
{
	int i;
	FILE *cities;

	cities = fopen("ukcities.txt", "r");
	if (cities == NULL)
		printf("Unable to open ukcities.txt\n");

	else {

		NPI *new_node;
		new_node = (NPI *) malloc(sizeof(NPI));
		new_node->next = NULL;
		fscanf(cities, "%s \t %s \t %d\n", new_node->city1,
			   new_node->city2, new_node->distance);
		gotoxy(20, 25);
		fprintf(stdout, "%s %s %d\n", new_node->city1, new_node->city2,
				new_node->distance);

	}

	fclose(cities);

	return 0;
}

int main(void)
{
	NPI *first = NULL, *current = NULL, *last = NULL;
	char response;

	system("cls");

	gotoxy(25, 18);
	printf("Enter 'a' to add all cars to list");
	gotoxy(40, 25);
	putch(' ');
	gotoxy(25, 25);
	printf("Enter command: ");
	response = getch();
	gotoxy(34, 40);
	putch(response);

	switch (response) {
	case 'a':
		current = last = add_nodes(last);
		break;
	}

	if (first == NULL)
		current = first = last;

	return 0;
}

The way which i intend for it to work at the moment is that upon the user entering 'a', all the data will be added to the linked list. The program compiles, but upon running, crashes. Im not certain that the code is correct! If anybody could lend me a hand i would be most grateful!

Thanks,

Charlie

One thing I see right away:

fscanf(cities, "%s \t %s \t %d\n", new_node->city1,
			   new_node->city2, [B]&[/B]new_node->distance);
Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.