Chinaunix首页 | 论坛 | 博客
  • 博客访问: 203849
  • 博文数量: 55
  • 博客积分: 1305
  • 博客等级: 中尉
  • 技术积分: 350
  • 用 户 组: 普通用户
  • 注册时间: 2010-12-11 15:18
文章分类

全部博文(55)

文章存档

2012年(1)

2011年(54)

分类: LINUX

2011-06-08 08:58:08

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, CON represents the standard input, so: #include "CON"
andromeda:/home/susam# cat reader.c #include "/dev/stdin" andromeda:/home/susam# gcc -o reader reader.c #include int main(int argc, char **argv) { printf("hello, world\n"); return 0; } andromeda:/home/susam# ./reader hello, world
Update: I have realized it and many people have pointed it out to me that the solution doesn't take input while compiling. Instead, it takes input while pre-processing. Unfortunately, I didn't think of this minor but important difference while writing this blog post. I could have changed the subject after I realized it but unfortunately, this blogging application doesn't allow me to change the URL. Hence, I left it unchanged.
阅读(1507) | 评论(0) | 转发(0) |
给主人留下些什么吧!~~