summaryrefslogtreecommitdiffhomepage
path: root/bilingual_sort.c
blob: 870e3da6ef1cff7274b74842809922afd08119c7 (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
/* This is a simple program that runs in an infinite loop.  It reads strings
 * from standard input in the form of “str1:str2”, sorts them according to the
 * locale (set by gawk), and then prints out the first string in sorted order.
 *
 * The reason we use this instead of just sort(1) or something is because
 * spawning one process for each comparison is super slow.  This lets us do
 * multiple comparisons of string-pairs in only a single process.
 */

#define _GNU_SOURCE

#include <locale.h>
#include <stdbool.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>

int
main(void)
{
	char *s1, *s2,
	     line[256];

	/* We need line buffering to make gawk interact with this properly */
	setlinebuf(stdout);
	setlocale(LC_ALL, "");

	while (true) {
		if (fgets(line, sizeof(line), stdin) == NULL)
			break;

		s1 = line;
		s2 = strchr(line, ':') + 1;
		s2[-1] = '\0';
		*strchrnul(s2, '\n') = '\0';

		puts(strcoll(s1, s2) < 0 ? s1 : s2);
	}

	return EXIT_SUCCESS;
}