I'm about to make code that read the text file line by line, then store it to stucture, then use quicksort. But my code doesn't print anything. Here is my code and text file.
#include <stdio.h>
#include <stdbool.h>
#include <string.h>
#include <stdlib.h>
struct city{
char nation[2];
char region[10];
char name[50];
int population;
double latitude;
double longitude;
};
struct city p1[100];
int compare_with_name(const void *a, const void *b)
{
struct city* ptr_a = (struct city*)a;
struct city* ptr_b = (struct city*)b;
if (ptr_a->name < ptr_b->name) return 1;
else if (ptr_a->name == ptr_b->name) return 0;
else return -1;
}
int compare_with_population(const void *a, const void *b)
{
struct city* ptr_a = (struct city*)a;
struct city* ptr_b = (struct city*)b;
if (ptr_a->population < ptr_b->population) return 1;
else if (ptr_a->population == ptr_b->population) return 0;
else return -1;
}
int compare_with_latitude(const void *a, const void *b)
{
struct city* ptr_a = (struct city*)a;
struct city* ptr_b = (struct city*)b;
if (ptr_a->latitude < ptr_b->latitude) return 1;
else if (ptr_a->latitude == ptr_b->latitude) return 0;
else return -1;
}
void split() {
FILE* fp;
fp = fopen("world_cities.txt", "r");
char buff[255];
char **a=(char**)malloc(20000000 * sizeof(char*));
int i=0;
char* tok;
char* split;
while(!feof(fp)){
fgets(buff,255,fp);
tok=strtok(buff,"\n");
split = (char* )malloc(strlen(tok) * sizeof(char));
strcpy(split, tok);
a[i]=split;
i++;
}
while (tok != NULL) {
tok = strtok(NULL, ",\n");
if (tok == NULL) {
break;
}
split = (char* )malloc(strlen(tok) * sizeof(char));
strcpy(split, tok);
a[i] = split;
i += 1;
}
for(int k=0;k<47913;k++){
scanf("%s %s %s %d %lf %lf",p1[k].nation,p1[k].region,p1[k].name,&p1[k].population,&p1[k].longitude,&p1[k].latitude);
}
fclose(fp);
}
int main(){
split();
qsort(p1,100,sizeof(struct city),compare_with_name);
for(int i=0;i<47913;i++){
printf("%s %d %lf %lf",p1[i].name, p1[i].population,p1[i].longitude,p1[i].latitude);
}
}