hello
i had trouble in finding out whats wrong with my code
I want to sort the data's from my text file and it somehow did but some of the words did not appear.
word.txt
hello
apple
hi
banana
mango
the output I get is :
hello
hello
hi
hi
mango
code:
#include<stdio.h>
#include<string.h>
#include<stdlib.h>
void sort_a(void *array, unsigned n);
static int cmpr(const void *a, const void *b);
int main ( void )
{
char line[1024];
const char *line_array[1000];
int i = 0;
int j = 0;
static const char filename[] = "text.txt";
FILE *file = fopen ( filename, "r" );
if ( file != NULL )
{
while ( fgets ( line, sizeof (line), file ) != NULL )
{
if (i < 1024)
line_array[i++] = strdup(line);
else
break;
sort_a(line_array, i);
printf("%s", line_array[j++]);
}
}
else
{
perror ( filename );
}
fclose ( file );
return 0;
}
int cmpr(const void *a, const void *b) {
return (strcmp(*(char **)a, *(char **)b));
}
void sort_a(void *array, unsigned n) {
qsort(array, n, sizeof(const char *), cmpr);
}
Thank you!