Sunday, October 18, 2009

Self Replicating Code

For a class recently the teacher challenged us to write a code snip-bit that would be self replicating. By that I mean write a program that when executed would write out its own source code. This is a bit harder than you'd initially think it to be. My first attempt tried to store the source code within the program when execute it would output what was stored within. However this creates a chick and egg problem. The source code contains the source code. Something that at first stumped me. Then I remembered Stringification in the C preprocessor and I came up with this:

#include "stdio.h"
#define M(Code) main(){FILE* fp = fopen("source.c", "w");fprintf(fp,"#include \"stdio.h\"\n#define M(Code) %s\nM(%s)\n",#Code,#Code);fclose(fp);}
M(main(){FILE* fp = fopen("source.c", "w");fprintf(fp,"#include \"stdio.h\"\n#define M(Code) %s\nM(%s)\n",#Code,#Code);fclose(fp);})


This is a pretty cute program if I can say so myself. When its ran it will create a file called source.c that will be exactly the same as the code above. You could even recompile source.c and it will create another source.c. You should attempt to do this on your own to see if you can come up with other cool ways of doing it.

Download: SelfRep.c