Home | Bio | My Life | Archive | Writings | Talks | Toons | Photos | Site | About | Contact | Feed
Line follower in quintessence.. Latest hit in my blog : Line follower and other Project updates

Saturday, February 9, 2008

A simple question....

Question:
I came across this tricky question in a set of aptitude questions
Write a small C program, which while compiling takes another programfrom input terminal, and on running gives the result for the secondprogram.
(NOTE: The key is, think UNIX).


Answer:
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"

chipmonks:/home/anilnf# cat reader.c
#include "/dev/stdin"
chipmonks:/home/anilnf# gcc -o reader reader.c
#include
int main(int argc, char **argv) { printf("hello, world!\n"); }
chipmonks:/home/anilnf# ./reader
hello, world!

No comments: