Exercise 1.17 - Print lines that are longer than 80 chars

Question

Write a program to print all input lines that are longer than 80 characters.

Solution

/**
 *
 * Exercise 1.17 -  Program to print the length of all input lines greater
 * than 80 characters.
 *
 **/

#include <stdio.h>

#define MAXLINE 1000
#define LIMIT 80

/***
 *
 * We call it _getline, for new getline so that it does not conflict with
 * system function getline
 *
 ***/

int _getline(char line[], int lim);

int main(void) {
    int len;
    char line[MAXLINE];

    while ((len = _getline(line, MAXLINE)) > 0) {
        if (len > LIMIT)
            printf("%s", line);
    }

    return 0;
}

int _getline(char line[], int lim) {
    int i, c;

    for (i = 0; i < lim - 1 && (c = getchar()) != EOF && c != '\n'; ++i)
        line[i] = c;

    if (c == '\n') {
        line[i] = c;
        ++i;
    }
    line[i] = '\0';

    return i;
}

Explanation

A string in C is a character array which ends in \0. getline is a function in our program, which reads one character at a time using getchar and stores it in a character array called s[] and it returns the length of the array.

When an array is sent as argument to the function, like line[MAXLINE] is sent to getline function, the value is passed by reference, which means that any changes the function makes will be available to the main program.

getline returns the length of the line and in our main program, if the length is greater than 80 characters we print it.