I have the following .txt file:
1 7 9 12
8 4 22 5
4 9 0 10
15 2 3 14
I wanna print the lines in descending order based on the average value on each individual line.
Code:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define MAX 300
int comp(const void *p, const void *q)
{
    float l = *(const float*)p;
    float r = *(const float*)q;
    return (r-l);
}
int main(int argc, char* argv[])
{
    if(argc != 2)
    {
        printf("Invalid format.\n");
        return -1;
    }
    FILE* fin = fopen(argv[1], "r");
    if(!fin)
    {
        printf("Error opening the file.\n");
        return 1;
    }
    char buf[MAX];
    int n, countLines = 0;
    float *avg;
    while(fgets(buf, MAX, fin))
    {
        avg = realloc(avg, (countLines+1)*sizeof(float*));
        float sum = 0;
        float countWords = 0;
        char* word = strtok(buf, " ");
        while(word)
        {
            countWords++;
            //printf("Word : %s\n",word);
            n = atoi(word);
            sum = sum+n;
            word = strtok(NULL, " ");
        }
        avg[countLines] =(float)(sum/countWords);
        countLines++;
    }
    qsort(avg, countLines, sizeof(float), comp);
    for(int i = 0; i < countLines; i++)
    {
        printf("%f\n", avg[i]);
    }
    free(avg);
    fclose(fin);
    return 0;
}
Output so far:
9.750000
8.500000
7.250000
5.750000
So I'm getting the right values, I just need to figure out how to print the actual lines, not the values. Any ideas?