summaryrefslogtreecommitdiff
path: root/ch1/no_trailers.c
blob: 80dbc0f3912d6a83d13cbd7e25a44b33443c33f3 (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
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
#include<stdio.h>

#define MAXLENGTH 1000

int get_line(char line[], int maxlength);
void strip_line(char line[], int length);
void copy(char to[], char from[]);

/*
 * MAIN
 * Removes all trailing whitespace and blank lines from STDIN.
 */
int main() {
    int len; // current line length
    char line[MAXLENGTH]; // current input line

    while ((len = get_line(line, MAXLENGTH)) > 0) {
        strip_line(line, len);
        if (line[0] != '\0')
            printf("%s\n", line);
    }
    return 0;
}

/*
 * GET_LINE
 * Read STDIN into LINE up to MAXLENGTH and return its length. 
 * Returns the length of a the line.
 */
int get_line(char line[], int maxlength) {
    int c, i;

    for (i = 0; i < maxlength - 1 && (c = getchar()) != EOF && c != '\n'; ++i)
        line[i] = c;
    if (c == '\n') {
        line[i] = c;
        ++i;
    }
    line[i] = '\0';
    return i;
}

/*
 * STRIP_LINE
 * Remove all whitespace from end of LINE of given LENGTH.
 */
void strip_line(char line[], int length) {
    int i, c;

    for (i = --length; i >= 0; --i) {
        c = line[i];

        if (c == ' ' || c == '\t' || c == '\n')
            line[i] = '\0';
        else 
            break;
    }
}


/*
 * COPY
 * Copy FROM into TO; assume TO is big enough.
 */
void copy(char to[], char from[]) {
    int i;

    i = 0;
    while ((to[i] = from[i]) != '\0')
        ++i;
}