Thursday, July 12, 2007

Interesting C Program -10

Quine Program: (A C Program that prints itself)


/*quine.c*/
#include"stdio.h"
int main()
{
FILE *fp1;
char x[100][100]={0};
int i;
fp1 = fopen("quine.c","r");
for(i=0;i<50;i++)
fgets(x[i],50,fp1);
for(i=0;i<50;i++)
printf("%s",x[i]);
}




But Can we call this a Quine Program?

The answer is NO.
Why?
Because, after compilation if you change the source code, new source file will be printed. Then how do you write a quine program?

Heres an implementation of Quine:


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

1 comment:

Peak said...

If you include the header file, the code can be like this.

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

Search Google

Books that I refer to...

  • The Complete Reference C, Fourth Edition
  • The C Programming Language