Lesson 5 of 23

wc -l

wc -l: Count Lines

wc -l counts the number of lines in a file:

$ wc -l notes.txt
3 notes.txt

A "line" in Unix means a string terminated by a newline character '\n'. A file with 3 newlines has 3 lines.

Your Implementation

Write int count_lines(const char *s) that counts the number of newline characters in the string.

int count_lines(const char *s) {
    int n = 0;
    while (*s) {
        if (*s == '\n') n++;
        s++;
    }
    return n;
}

Simple: walk the string, increment the counter every time you see '\n'.

A Common Use Case

Counting lines is incredibly useful in pipelines:

ls | wc -l          # how many files?
grep "error" log | wc -l    # how many errors?

The output of one command flows into wc -l, which tells you how many lines (i.e., how many results) there were.

Your Task

Implement count_lines that returns the number of newline characters.

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