#include <stdio.h>
#include <fcntl.h>
#include <errno.h>
#include <unistd.h>
#include <string.h>
#include <stdlib.h>
#include <errno.h>
#include <limits.h>
#include <stdlib.h>
for the program I have an array of char * named arr[] and I am trying to sort it alphabetically but having no luck doing so it does nothing when running the for loop at the end. I want to keep the offset[] with arr[] so because I need the char code and the offset for a file
typedef struct country {
char code_name[4];
char name[45];
int population;
float life_expect;
}country;
country data[240];
int main(void) {
char *swap;
int a=0,c=0,d=0,n=0;
int cmp = 1;
heres the arr[]
char *arr[239];
size_t offset[239];
char *ptr;
int i = 0;
int temp;
char buf[512];
char *token;
char buf_write[10000];
size_t nbytes_written;
size_t t_nbytes;
FILE *fptr;
fptr = fopen("AllCountries.dat", "r");
int wptr;
wptr = open("BinaryAllCountries.dat", O_RDWR);
FILE *rptr;
rptr = fopen("BinaryAllCountries.dat", "r");
do {
if (fgets(buf, 512 , fptr)){
//printf("%s\n",buf);
token = strtok(buf,",;");
while (token != NULL){
token = strtok(NULL, ",;");
if (temp == 0){
strcpy(data[i].code_name, token);
nbytes_written = write(wptr, token, strlen(token));
t_nbytes = t_nbytes + nbytes_written;
//printf("code_name: %s\n", data[i].code_name);
}
if (temp == 1){
strcpy(data[i].name, token);
cmp = strcmp(data[i].name, "Virgin Islands");
nbytes_written = write(wptr, token, strlen(token));
t_nbytes = t_nbytes + nbytes_written;
//printf("name: %s\n", data[i].name);
}
if (temp == 6){
data[i].population = atoi(token);
nbytes_written = write(wptr, token, strlen(token));
t_nbytes = t_nbytes + nbytes_written;
//printf("population: %i\n", data[i].population);
}
if (temp == 7){
data[i].life_expect = atof(token);
nbytes_written = write(wptr, token, strlen(token));
t_nbytes = t_nbytes + nbytes_written;
//printf("life expectancy: %f\n", data[i].life_expect);
}
temp = temp + 1;
}
arr[i] = data[i].code_name;
offset[i] = t_nbytes;
/*
printf("%s\n",arr[i]);
printf("%lu\n", offset[i]);
*/ printf("--------\n");
i = i + 1;
temp = 0;
}
}while (!feof(fptr));
here is where I tried to sort the array but nothing happens and the array stays the same
for (c = 0 ; c < 10; c++){
for (d = 0 ; d < 238; d++){
if (arr[d] > arr[d+1]){
swap = arr[d];
arr[d] = arr[d+1];
arr[d+1] = swap;
}
}
}
for (i = 0; i <239; i++){
printf("%s\n",arr[i]);
}
here is what some of the output looks like from the arr[] as you can see it doesn't get sorted
DZA AGO BEN BWA IOT BFA BDI CMR CPV CAF TCD COM COG COD CIV DJI EGY GNQ ERI ETH GAB GMB GHA GIN GNB KEN LSO LBR LBY MDG MWI MLI MRT
qsort()char *and asize_t(oroff_t, if it is a file offset) members, use an array of such structs, and sort it withqsort()and your own comparison function. The man 3 bsearch man page has an example of qsorting an array of structs.