Supposing your numbers are floats listed separate lines of your file:
- Create an array of float. If your don't know how many numbers you have, use a very large array (Note: in the example below, I created an array number_array of size 100)
- Read your file
- For each line of your file, store the number in the array you created in step 1
- After reading the whole file, sort the array. Note that in the example below, I use the function
qsort
to sort the array (see manual with command man qsort ;) )
- Write the content of your sorted array in your file
Example:
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#define LINE_SIZE 1024
// Comparison function used for sorting
int compare (const void * a, const void * b)
{
float fa = *(float*) a;
float fb = *(float*) b;
return (fa > fb) - (fa < fb);
}
// -------------------------------------------------------------
int main()
{
FILE *f;
char line[LINE_SIZE], *p;
int i = 0, j;
// YOUR NUMBER ARRAY
float number_array[100];
// Open file
if (!(f = fopen("numbers.txt", "r"))) {
fprintf(stderr, "Unable to open file argument\n");
return 1;
}
// Read lines from file
while (fgets(line, LINE_SIZE, f)) {
// You may want to remove the trailing '\n'
if ((p = strchr(line, '\n'))) { *p = '\0'; }
// Skip empty lines
if (line[0] == '\0') { continue; }
// Adding number to array
number_array[i] = atof(line);
i++;
}
// Closing file
fclose(f);
// Sorting array
qsort (number_array, i, sizeof(float), compare);
// Displaying result 8-)
// for (j=0; j<i; j++)
// {
// printf("%0.2f ", number_array[j]);
// }
// printf("\n");
// Writing sorted result to file
if (!(f = fopen("numbers.txt", "w"))) {
fprintf(stderr, "Unable to open file argument\n");
return 1;
}
for (j=0; j<i; j++)
{
fprintf(f, "%0.2f\n", number_array[j]);
}
fclose(f);
return 0;
}