Sunday, 5 October 2014

fgets and fputs

In this article we explore the use of fgets and fputs to deal with piped input. Admittedly, it is a rather roundabout way, but it can be useful in specific situations.

int main()
{
    char buf[10];
    while (fgets(buf, 10, stdin) != NULL) {
        fputs(buf, stdout);
    }
    fflush(stdout);
}


char buf[10] creates a buffer of size 10 (an arbitrary choice). This is where the piped input will be stored temporarily. It will be overwritten when the new batch of data arrives.

fgets is the function that actually gets the piped input from stdin, i.e. the standard input. The standard input is where pipes lead. The contents are obtained and placed into buf, 10 chars at a time. If this exceeds the buffer size, an overflow will occur! Once an end of file condition is reached, it will return NULL. Thus, the contents of the loop will be executed until the piped input ends. The actual work, e.g. transposing, changing all to capitals, etc. is done inside this while loop.

Finally, once we are done, we call fflush to actually commit the output (e.g. to the console). Note that fflush could have been called automatically earlier by the system; this call is just to flush whatever's remaining. In fact, there is no need to call it if your code returns after that. This is useful in service-like programs, that continuously takes piped input at intervals; you would use it to immediately produce the output, instead of waiting until the underlying system calls it.

Once the source is compiled, here's how you can try it out in cmd (replace main.exe with the name of your executable):

echo Here is my text | main.exe

The vertical bar ("|") is called a pipe. Echo always writes to the standard output, and this is piped to the standard input of main.exe.

No comments:

Post a Comment