A few years back I was thinking about ways to make a program that prints its own source code and I came up with these two approaches:

  • the program prints the .c or .cpp file based upon the executable name (app1 prints app1.cpp). but this will fail in case the .cpp file is located somewhere else.
  • the program makes "clever" use of strings (I forgot the source code of this), and prints itself.

Is there any other algorithm a program can use to print its own source code?

有帮助吗?

解决方案

I think your two cases cover all the options. Case (1) covers cases of the form "load the program source from an external device," while case (2) covers cases of the form "generate the program source programmatically." You could of course consider a hybrid approach like "read the first half of the program from a file and then generate the second half programmatically," but this doesn't seem any different from what you described above.

其他提示

As Steve pointed out in comments case 1) is usually not considered a quine, probably becasue its essetially trivial to do in any language that can do file I/O

case 2) is what most people mean when they say quine, the 'clever use of strings' being the part you are showing off with.

in some languages there is a 3rd case (which is also not usually counted as a true quine as it is even more trivial than case 1). If a language allows a program with no statements in at all to be well formed then this 'empty' program will usual print nothing, which is of course the same as its source code. e.g. the TCL script:

will print:

;)

A program need not be an "executable" with a particular "name", and the source code need not be in a "file" with a particular "name". These are all artifacts of modern operating systems, totally irrelevant to the job at hand.

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

(in one line)

there are many codes like this in http://www.nyx.net/~gthompso/quine.htm

to me this is the best way: assign code to variable and use it repeatly.

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top