1#include <stdio.h>
2#include <string.h>
3#include <ctype.h>
4
5/*
6 * Remove empty lines from the beginning and end.
7 *
8 * Turn multiple consecutive empty lines into just one
9 * empty line. Return true if it is an incomplete line.
10 */
11static int cleanup(char *line)
12{
13 int len = strlen(line);
14
15 if (len > 1 && line[len-1] == '\n') {
16 do {
17 unsigned char c = line[len-2];
18 if (!isspace(c))
19 break;
20 line[len-2] = '\n';
21 len--;
22 line[len] = 0;
23 } while (len > 1);
24 return 0;
25 }
26 return 1;
27}
28
29int main(int argc, char **argv)
30{
31 int empties = -1;
32 int incomplete = 0;
33 char line[1024];
34
35 while (fgets(line, sizeof(line), stdin)) {
36 incomplete = cleanup(line);
37
38 /* Not just an empty line? */
39 if (line[0] != '\n') {
40 if (empties > 0)
41 putchar('\n');
42 empties = 0;
43 fputs(line, stdout);
44 continue;
45 }
46 if (empties < 0)
47 continue;
48 empties++;
49 }
50 if (incomplete)
51 putchar('\n');
52 return 0;
53}