Tuesday, November 13, 2007

Compiler taking input while compiling

I came across this tricky question in a blog.
Write a small C program, which while compiling takes another program from input terminal, and on running gives the result for the second program. (NOTE: The key is, think UNIX).
At first it looked like a strange puzzle. How can a C code force the compiler to request for input while it is already compiling the code? After a little thinking, the solution became obvious.

The answer lies in a tricky use of the #include directive. We use #include directive to direct the compiler to read another file and include it in the source code. So, why not use it to read the standard input?

So, the code will have only one line: #include "/dev/stdin"
On Windows machine, the input is read from CON, so: #include "CON"

andromeda:/home/susam# cat reader.c
#include "/dev/stdin"

andromeda:/home/susam# gcc -o reader reader.c
#include <stdio.h>
int main(int argc, char **argv) { printf("hello, world!\n"); }

andromeda:/home/susam# ./reader
hello, world!

3 comments:

Vallabha said...

Very simple and very neat solution. Yet another complex puzzle with a simple solution :)

MS Vivek Chaitanya said...

WoW!

hey Susam, can you please add Feed to your blog so that I can subscribe to your blog in my Google Reader.

Thank you.

ಶರತ್ ಹೆಗಡೆ said...

Thanks.. It was bugging my head for long ...

Post a Comment