A program that prints its own text.

Don't peek unless you are done working on the problem!


























Answers by McKeeman

To make a program self-printing before it runs, in general prepend to the program two statements: a string assignment and a print statement. Within the string the whole program appears literally and also secretly in the form of a %s which will be filled in by the program string itself. One has to do a little work to get the line feeds and quotes right and make sure the requisite paraphernalia of program syntax are provided.

Here is a variety of solutions (of varying quality).

First, the easiest problem: the program only prints itself.

  • selfprint.c from the internet
    +------------------------------------------------------------------------------+
    |main(char*a){a="main(char*a){a=%c%s%c;printf(a,34,a,34);}";printf(a,34,a,34);}|
    +------------------------------------------------------------------------------+
    
  • selfprint.c using the file system (cheap trick)
    +-------------------------------------------+
    |main(int a, char **argv) {printf(argv[1]);}|
    +-------------------------------------------+
    
    Compile it and then run it thusly
    +-------------------------+
    |a.out "`cat selfprint.c`"|
    +-------------------------+
    
  • selfprint.m for an R13 MATLAB script.
    +------+
    |ans = |
    |      |
    |     3|
    +------+
    
  • traditional selfprint.m for any MATLAB script.
    +----------------------------------------------------------------+
    |a='a=%c%s%c;fprintf(1,a,39,a,39,10);%c';fprintf(1,a,39,a,39,10);|
    +----------------------------------------------------------------+
    

Now, suppose we have some quote-free script P.

  • selfprint.m for MATLAB script P:
    +--------------------------------------------------------------------+
    |a='a=%c%s%c;fprintf(1,a,39,a,39,10);P;%c';fprintf(1,a,39,a,39,10);P;|
    +--------------------------------------------------------------------+
    
  • For any MATLAB script P:
    +------+
    |type P|
    |P     |
    +------+
    
  • For the unix shell csh, let file x contain
    +-----+
    |cat x| 
    +-----+
    
    and in csh do
    +--------+
    |source x|
    +--------+
    
  • see also ~mckeeman/src/m ~mckeeman/src/c