imjacob的专栏

首页博文目录订阅
正 文

如何编写能够打印自己的程序

(2008/12/10 20:45)

如何编写能够打印自己的程序,我想方法无外乎三种。一种是利用文件操作,一种是利用元数据,而这里要讲的是第三种,叫做Quine。
什么是Quine?wiki上http://en.wikipedia.org/wiki/Quine_(computing)
是这么定义的:
in computing, a quine is a program, a form of metaprogram, that produces its complete source code as its only output. A quine can be considered to be a fixed point of an execution environment, when the execution environment is viewed as a function. For amusement, programmers sometimes attempt to develop the shortest possible quine in any given programming language.
下面给个c的例子:

 
 
#include <stdio.h>
 
int main(int argc, char** argv)
{
/* This macro B will expand to its argument, followed by a printf
 command that prints the macro invocation as a literal string */
#define B(x) x; printf("  B(" #x ")\n");
 
/* This macro A will expand to a printf command that prints the
 macro invocation, followed by the macro argument itself. */
#define A(x) printf("  A(" #x ")\n"); x;
 
/* Now we call B on the text of the program
 up to this point. It will execute the command, and then cause
 itself to be printed. */
  B(printf("#include <stdio.h>\n\nint main(int argc, char** argv)\n{\n/*
    This macro B will expand to its argument, followed by a printf\n
    command that prints the macro invocation as a literal string
    */\n#define B(x) x; printf(\"  B(\" #x \")\\n\");\n\n/* This macro
    A will expand to a printf command that prints the\n
    macro invocation, followed by the macro argument itself. */\n#define A(x)
    printf(\"  A(\" #x \")\\n\"); x;\n\n/* Now we call B on the text
    of the program\n up to this point. It will execute the command,
    and then cause\n itself to be printed. */\n"))
  A(printf("/* Lastly, we call A on a command to print the remainder
    of the program;\n it will cause itself to be printed, and then
    execute the command. */\n}\n"))
/* Lastly, we call A on a command to print the remainder of the program;
 it will cause itself to be printed, and then execute the command. */
}
 

 

 #define B(x) int main(){x; puts("B(" #x ")");}
B(puts("#define B(x) int main(){x; puts(\"B(\" #x \")\");}"))

 

  

 
main() { char *s="main() { char *s=%c%s%c; printf(s,34,s,34); }"; printf(s,34,s,34); }

我发现这些似乎都是在print,define之类的技巧,虽然很漂亮,但总感觉怪怪的,程序本身的可读性不好。
还有一个各种语言实现的程序例子:http://www.nyx.net/~gthompso/quine.htm

评 论
还没有网友评论,欢迎您第一个评论!
博 主
进入imjacob的首页
博客名称:雅克的一府
日志总数:514
评论数量:901
访问次数:1869647
建立时间:2006/11/23 20:52
导 航
公 告
Locations of visitors to this page 本博客主要用于个人学习与资料收藏。当然大家应该读了之后也能学到不少东西。其中大多数资料都是来自网络,我转载时尽可能地表明文章出处与原作者姓名,但由于很多资料经多人转载,已不清楚原作者信息与出处,所以未表明相关…
评 论
链 接

ARM+LINUX 嵌入式博客
http://blog.chinaunix.net/u1/58780/index.html

嵌入式软件
http://blog.csdn.net/embeddedsoft

诚诚恳恳做人踏踏实实编程
http://blog.sina.com.cn/u/1244756857 

和我风格相似的一个blog
http://blogger.org.cn/blog/m…