Codiqo

Learn C · lesson 32 of 60 · about 10 minutes

Project: Log Search

Search the system log: read lines with fgets until end, find the ones with errors in them using strstr, and keep the longest.

What you'll learn

  • Read lines until a stop word
  • Search text with strstr
  • Copy the line worth keeping with strcpy

The plan

The machine's log is typed in one line at a time, ending with a line that just says end. The report:

1. Reads each line with fgets and removes its newline
2. Stops at end, or when the input runs out
3. Prints every line with the word error in it, with its line number
4. Keeps a copy of the longest line, and finishes with the counts

Finding text inside text

strstr(line, "error") looks for error anywhere in line. It returns a pointer to where it starts, or NULL if it isn't there, so strstr(...) != NULL means found. Like strcmp, it's case-sensitive: Error with a capital doesn't match.

Lines until end

#include <stdio.h>
#include <string.h>

int main(void) {
    char line[80];
    int count = 0;
    while (fgets(line, sizeof line, stdin) != NULL) {
        line[strcspn(line, "\n")] = '\0';
        if (strcmp(line, "end") == 0) {
            break;
        }
        count++;
        if (strstr(line, "warn") != NULL) {
            printf("Line %d warns: %s\n", count, line);
        }
    }
    printf("%d lines\n", count);
    return 0;
}

Output

Line 1 warns: fan warning
2 lines

Tip

while (fgets(...) != NULL) keeps reading until there's no more input, because fgets returns NULL at the end. The break handles the stop word, and the loop's own test handles a log with no end line.

Tip

To keep the longest line, copy it with strcpy into an array of its own. Remembering line itself isn't enough: the next fgets writes over it.

Now try it yourself

This lesson is free in Codiqo, with 8 questions on what you just read. You can only learn to code by writing code, so it ends with a short program you write yourself, which we run and check straight away.