/* Copyright 2005 Daniel Cer (daniel.cer@cs.colorado.edu) This work is licensed under the Creative Commons Attribution-NonCommercial- ShareAlike License. To view a copy of this license, visit http://creativecommons.org/licenses/by-nc-sa/2.5/ or send a letter to Creative Commons, 543 Howard Street, 5th Floor, San Francisco, California, 94105, USA. */ #include #include #define INBUF_SZ 1024 /* comparison routine used with 'qsort' call */ int cmp_float(const void *a, const void *b){ return *(float*)a - *(float*)b; } int main(int argc, char *argv[]) { FILE *fh; char *file_name, inbuf[INBUF_SZ]; int N_items, i; float *items; if (argc != 2) { fprintf(stderr, "Usage:\n\t%s (file with numbers to sort)\n", argv[0]); return -1; } file_name = argv[1]; if (!(fh = fopen(file_name, "r"))) { fprintf(stderr, "Error opening \"%s\": %s\n", file_name, strerror(errno)); return -1; } /* determine the number of items listed in the file */ for (i = 0; fgets(inbuf, INBUF_SZ, fh); i++); N_items = i; fseek(fh, 0, SEEK_SET); /* allocate memory to store the items */ if (!(items = malloc(sizeof(float)*N_items))) { fprintf(stderr, "Error: out of memory\n"); return -1; } /* read in the items from the file */ for (i=0; fgets(inbuf, INBUF_SZ, fh); i++) sscanf(inbuf, "%f\n", &items[i]); fclose(fh); /* sort them */ qsort(items, N_items, sizeof(float), &cmp_float); /* display the sorted items */ for (i = 0; i < N_items; i++) { printf("%f\n", items[i]); } free(items); return 0; }