Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I write a filter program in C?

Tags:

c

filter

Since UNIX has all those wonderful filter-like programs (such as grep, sed, tr and so forth), what's the easiest way to write one of those in standard C?

By filter, I mean a program which reads standard input, performs some manipulation of the data, and then writes it to standard output. This is useful in constructing pipelines of commands, with each performing some additional manipulation of the data, such as:

grep xyzzy input.file | tr '[A-Z]' '[a-z]' | sed 's/plugh/PLUGH/g'

(each of the | pipe symbols connects the standard output of the previous command to the standard input of the next, hence the pipeline metaphor).

Let's say I needed one that converted all uppercase characters to lowercase. And, yes, I realise this particular problem can be solved with the UNIX:

tr '[A-Z]' '[a-z]'

but that's just an example.

What I'm actually after is the simplest standard C source code to do such a filter.

like image 526
paxdiablo Avatar asked Apr 03 '12 07:04

paxdiablo


People also ask

What is filter program in C?

A "filter" program is simply a program which reads from the standard input stream ( stdin ) and writes to the standard output stream ( stdout ).

What is filter syntax?

Syntax. The FILTER function filters an array based on a Boolean (True/False) array. =FILTER(array,include,[if_empty]) Argument. Description.

What is a filter program?

In computer applications, a filter is a program or section of code that's designed to examine each input or output request for certain qualifying criteria and then process or forward it accordingly.


1 Answers

You could use getline as described by @hroptatyr, but you can do something a lot simpler:

#include <stdio.h>
#include <ctype.h>
int main(void) {
    int c;
    while ((c = getchar()) != EOF)
        putchar(tolower(c));
    return 0;
}
like image 174
zmbq Avatar answered Oct 21 '22 22:10

zmbq