Exercise 1-18

Write a program to remove trailing blanks and tabs from each line of input, and to delete entirely blank lines.

We use getline to read our lines into line and store their lengths into len. After reading in a line, we execute a loop that runs as long as line[len-2]—the last character before the newline—is a space or a tab and len is greater than 1. To delete the trailing whitespace, during every iteration, we replace line[len-1] (previously a newline) with \0, replace line[len-2] (previously a space or tab) with a newline, and decrement len. Once we exit the loop, we only print the line if its length is greater than 1.

    #include <stdio.h>
    
    #define MAXLINE 1000    /* maximum input line size */
    
    int my_getline(char line[], int maxline);
    
    main()
    {
        int len;            /* current line length */
        char line[MAXLINE]; /* current input line */
    
        while ((len = my_getline(line, MAXLINE)) > 0) {
            while (len > 1 && (line[len-2] == ' ' || line[len-2] == '\t')) {
                line[len-1] = '\0';
                line[len-2] = '\n';
                --len;
            }
            if (len > 1)    /* ignore entirely blank lines */
                printf("%s", line);
        }
        return 0;
    }

Note: notice how in the while-loop that deletes the trailing spaces, we check if len > 1 first. This is important because if len was less than 1 and we did not check it first, line[len-2] would be accessing a negative index.