Line Filters in C
A line filter is a common type of program that reads input on stdin, processes it, and then prints some derived result to stdout. grep
and sed
are common line filters.
Here’s an example line filter in C that writes a capitalized version of all input text. You can use this pattern to write your own C line filters.
#include <stdio.h>
#include <string.h>
#include <ctype.h>
#define MAX_LINE_LENGTH 1000
void capitalize(char *str) {
for (int i = 0; str[i]; i++) {
str[i] = toupper((unsigned char) str[i]);
}
}
int main() {
char line[MAX_LINE_LENGTH];
// Read input line by line
while (fgets(line, sizeof(line), stdin)) {
// Remove newline character if present
line[strcspn(line, "\n")] = 0;
// Capitalize the line
capitalize(line);
// Print the capitalized line
printf("%s\n", line);
}
// Check for errors during reading
if (ferror(stdin)) {
fprintf(stderr, "Error reading input\n");
return 1;
}
return 0;
}
This program uses fgets()
to read input line by line from stdin. Each line is then capitalized using a custom capitalize()
function, which uses the toupper()
function from ctype.h
. The capitalized line is then printed to stdout using printf()
.
To try out our line filter, first make a file with a few lowercase lines.
$ echo 'hello' > /tmp/lines
$ echo 'filter' >> /tmp/lines
Then compile and use the line filter to get uppercase lines.
$ gcc -o line_filter line_filter.c
$ cat /tmp/lines | ./line_filter
HELLO
FILTER
This C version achieves the same functionality as the original program. It reads input line by line, capitalizes each line, and prints the result. Error checking is done at the end of the program to ensure all input was read successfully.