11

Sort a file by line

  1. #include <stdio.h>
  2. #include <stdlib.h>
  3. #include <string.h>
  4.  
  5. #define MAXLINES    10000
  6.  
  7. static char *lines[ MAXLINES ];
  8.  
  9. static int cmp(const char **s1, const char **s2) {
  10.     return strcmp( *s1, *s2);
  11. }
  12.  
  13. #include <stdlib.h>
  14.  
  15. main() {
  16.     char buf[ 4096 ];
  17.     int nlines = 0;
  18.     int i;
  19.  
  20.     while (fgets(buf, sizeof (buf), stdin) ) {
  21.         char *s = (char *)malloc(strlen(buf) + 1);
  22.         lines[ nlines ] = strcpy(s, buf);
  23.         if ( ++nlines == MAXLINES)
  24.             break;
  25.     }
  26.     qsort(lines, nlines, sizeof(char *),
  27.             (int (*)(const void *, const void *))cmp );
  28.     for (i = 0; i < nlines; ++i)
  29.         fputs(lines[ i ], stdout);
  30. }
$ gcc -o fslines fslines.c
$ ./fslines < fromages.txt
Abondance
Beaufort
Bleu-d'Auvergne
...
Salers
Selles-sur-Cher
Ste-Maure-de-Touraine

Comments

Your comment:
[p] [b] [i] [u] [s] [quote] [pre] [br] [code] [url] [email] strip help 2000

Enter a maximum of 2000 characters.
Improve the presentation of your text with the following formatting tags:
[p]paragraph[/p], [b]bold[/b], [i]italics[/i], [u]underline[/u], [s]strike[/s], [quote]citation[/quote], [pre]as is[/pre], [br]line break,
[url]http://www.izend.org[/url], [url=http://www.izend.org]site[/url], [email]izend@izend.org[/email], [email=izend@izend.org]izend[/email],
[code]command[/code], [code=language]source code in c, java, php, html, javascript, xml, css, sql, bash, dos, make, etc.[/code].