File: gl-sort.c

package info (click to toggle)
emacs-manual-ja 20.5-1
  • links: PTS
  • area: main
  • in suites: potato
  • size: 2,964 kB
  • ctags: 12
  • sloc: lisp: 119; ansic: 69; makefile: 43; sh: 28
file content (96 lines) | stat: -rw-r--r-- 2,012 bytes parent folder | download
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
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
/*						Atuo Ohki, 1998 Oct 23
 * sort glossary.texi for AIUEO order
 * assuming
 *	some text
 *	@c ==jtable			<-- head of sort section
 *	@c ==jitem Hiragana-Yomi	<-- item delemiter & sort key
 *	  .....
 *	@c ==jend			<-- tail of sort section
 *	some text
 */

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

#define MAX_LINES 10000
#define LNSIZE  1000

struct ln_link {
  struct ln_link *ln_next;
  char ln_char[4];
} *lines[MAX_LINES];

/* compare ln_link */
static int
ln_cmp(const void *a, const void *b)
{
  struct ln_link *la = *((struct ln_link**)(a));
  struct ln_link *lb = *((struct ln_link**)(b));

  return strcmp(&(la->ln_char[0]), &(lb->ln_char[0]));
}

/* save line `cp' and return ln_link */
struct ln_link *
save_ln(char *cp)
{
  struct ln_link *v;
  char *l;

  if (v = (struct ln_link*) malloc(sizeof(struct ln_link) + strlen(cp) + 1)) {
    v->ln_next = NULL;
    strcpy(&(v->ln_char[0]), cp);
  } else
    v = NULL;
  return v;
}

main()
{
  char ln[LNSIZE];
  int ln_count;
  int i;
  struct ln_link *lnp;

  ln_count = -1;
  /* preamble */
  while (fgets(ln, LNSIZE, stdin) == ln) {
    if (strncmp(ln, "@c ==jtable", 11)) {
      fputs(ln, stdout);
      continue;
    }
    ln_count = 0;
    break;
  }
  if (ln_count == 0) {
    /* jtable  jitem ...  jend */
    lnp = NULL;
    while (fgets(ln, LNSIZE, stdin) == ln) {
      if (strncmp(ln, "@c ==jitem ", 11) == 0) {
	/* make entry */
	lnp = lines[ln_count++] = save_ln(ln);
      } else if (strncmp(ln, "@c ==jend", 9) == 0) {
	break;
      } else if (lnp) {
	lnp->ln_next = save_ln(ln);
	lnp = lnp->ln_next;
      }
    }
    printf("@c == %d items\n", ln_count);
    /* sort them */
    if (ln_count > 0)
      qsort(lines, ln_count, sizeof(lines[0]), ln_cmp);
    /* print them */
    for (i=0; i<ln_count; i++) {
      lnp = lines[i];
      while (lnp) {
	fputs(&(lnp->ln_char[0]), stdout);
	lnp = lnp->ln_next;
      }
    }
  }
  /* postamble */
  while (fgets(ln, LNSIZE, stdin) == ln)
    fputs(ln, stdout);
}