Monday, May 07, 2007

Program Printing Its Source Code

I get asked this a lot. For some reason, many people want to write programs that display their own source code upon execution, and most of those people don't use Google. So I just decided to write something up and put it here. It's by no means short or concise. It's midnight for crying out loud!
   1:#include <stdio.h>
   2:const char pre [] = {32, 32, 32, 32, 34};
   3:const char post [] = {34, 44, 10};
   4:const char * lines [] = {
   5:    "#include <stdio.h>",
   6:    "const char pre [] = {32, 32, 32, 32, 34};",
   7:    "const char post [] = {34, 44, 10};",
   8:    "const char * lines [] = {",
   9:    "};",
  10:    "int main ()",
  11:    "{",
  12:    "    for (size_t i = 0; i < 4; ++i)",
  13:    "        puts (lines[i]);",
  14:    "    for (size_t i = 0; i < sizeof(lines) / sizeof(const char *); ++i)",
  15:    "    {",
  16:    "        printf (pre);",
  17:    "        printf (lines[i]);",
  18:    "        printf (post);",
  19:    "    }",
  20:    "    for (size_t i = 4; i < sizeof(lines) / sizeof(const char *); ++i)",
  21:    "        puts (lines[i]);",
  22:    "    return 0;",
  23:    "}",
  24:};
  25:int main ()
  26:{
  27:    for (size_t i = 0; i < 4; ++i)
  28:        puts (lines[i]);
  29:    for (size_t i = 0; i < sizeof(lines) / sizeof(const char *); ++i)
  30:    {
  31:        printf (pre);
  32:        printf (lines[i]);
  33:        printf (post);
  34:    }
  35:    for (size_t i = 4; i < sizeof(lines) / sizeof(const char *); ++i)
  36:        puts (lines[i]);
  37:    return 0;
  38:}
  39:

This is the simplest exact solution I could come up with (not the shortest.) Note that if you run this program and then run the output again and again, it generates exactly the same result. Note that the indentation is done with spaces, not tab characters.
There's a name for this kind of program and I think it starts with a 'p', but I can't be certain.

No comments: