Im trying to sort a array of strings I read from a file in alphabetical order using the qsort
function. This is my code:
#include<stdio.h>
#include<stdlib.h>
#include<io.h>
#define MAXCHAR 256
int main(int argc, char **argv){
char tempList[MAXCHAR][MAXCHAR];
char reader[MAXCHAR];
FILE* fp;
int i;
char *n;
int index = 0;
if(argc != 2){
printf("too few arguments\n");
exit(-1);
}
fp=fopen(argv[1], "r");
if(fp == NULL){
printf("failed to open file\n");
exit(-1);
}
while(!feof(fp)){
fgets(reader, MAXCHAR, fp);
n = strchr(reader, '\n');
if(n != NULL){
*n = '\0';
}
strcpy(tempList[index], reader);
index++;
}
index--;
for(i=0; i<index; i++){
printf("%s\n", tempList[i]);
}
qsort(tempList, index, sizeof(char *), strcmp);
for(i=0; i<index; i++){
printf("%s\n", tempList[i]);
}
}
When I run the program, the list doesn't get sorted at all. I also tried methods posted on this website that asks a similar question and they all give me segmentation faults. Is there something wrong with the code?
Here is part of the content of the txt file. It is a list of 40 names:
Liam
Alexander
Mia
Noah
Emma
William
Charlotte
Charlotte
Mason
William
Ethan
Ethan
Liam
Alexander
Liam
Sophia
Emily
Mason
Alexander