Lesson 7 of 23

head

The head Command

head -n N prints the first N lines of its input:

$ head -n 2 notes.txt
Learn Linux
Practice daily

Your Implementation

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

The algorithm: walk the string, printing each character. Keep a counter of how many newlines you have seen. Stop when you have printed n complete lines.

void my_head(const char *s, int n) {
    int lines = 0;
    while (*s && lines < n) {
        putchar(*s);
        if (*s == '\n') lines++;
        s++;
    }
}

Notice that the line count increments after printing the newline — so the newline is included in the output. This means "printing a line" includes its terminating \n.

Early Exit

The while (*s && lines < n) condition exits as soon as either:

  • We reach the end of the string (*s == '\0')
  • We have printed n complete lines (lines == n)

This is more efficient than the real head, which exits as soon as N lines have been written so that cat hugefile.txt | head -n 1 does not read the whole file.

Your Task

Implement my_head that prints the first n lines of the string.

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