Lesson 8 of 23

tail

The tail Command

tail -n N prints the last N lines of its input:

$ tail -n 2 notes.txt
Practice daily
Have fun

Your Implementation

Write void my_tail(const char *s, int n) that prints the last n lines.

head was easy: scan forward, stop after N newlines. tail is harder because you do not know where the last N lines start until you have seen the whole string.

The approach:

  1. Find the length of the string
  2. Scan backwards from the end (skipping the trailing newline), counting newlines
  3. Once you have counted n newlines, everything after that position is the last n lines
void my_tail(const char *s, int n) {
    int len = 0;
    while (s[len]) len++;

    // Skip trailing newline for counting
    int end = (len > 0 && s[len - 1] == '\n') ? len - 1 : len;

    int count = 0;
    int start = 0;
    for (int i = end - 1; i >= 0; i--) {
        if (s[i] == '\n') {
            count++;
            if (count == n) {
                start = i + 1;
                break;
            }
        }
    }
    printf("%s", s + start);
}

Two Passes

This is a two-pass algorithm: first pass finds the length, second pass scans backwards. The real tail uses a circular buffer to do it in one pass, but the two-pass approach is clear and correct.

Your Task

Implement my_tail that prints the last n lines.

TCC compiler loading...
Loading...
Click "Run" to execute your code.