Thursday, 10 January 2013

Self-Replicating C Programs (Quine)

  A program with no input, which prints the same program as output is called Quine. They are also called self-replicating programs, self-reproducing programs or self-copying programs. Given below is a Quine program in C. The program uses the predefined macro __FILE__ to open and print the program itself as output.

#include<stdio.h>
int main()
{
    FILE *fp;
    char c;
    fp=fopen(__FILE__,"r");
    do
    {
       c=getc(fp);
       putchar(c);
    }while(c!=EOF);
    fclose(fp);
    return 0;
}


Download.

Figure Below Shows the Output

  But the program I wrote is not a clever one, it just uses the file as input and prints it. But I have come across a brilliant program in one of the discussion forums, which replicates itself without using the file. The Program is given below for which the unknown author deserves full credit.

#include <stdio.h>
char*s="#include <stdio.h>%cchar*s=%c%s%c;%cint main(void){printf(s,10,34,s,34,10,10);}%c";
int main(void){printf(s,10,34,s,34,10,10);}

Download.

Figure Below Shows the Output
 

No comments:

Post a Comment