Friday, July 27, 2012

Printing source code of the program itself in C!!


The concept of printing the source code of the program itself is called quine. Here we will see the implementatin of printing source code of the program in C language.

How it works: As quine concept says, to implement this, we need to see the whole program in two parts like code and data where data is the textual form of code. So most cases data is the code which placed between the quotes. Below is the simple C program to print source code.

main()
{
char str[]="main(){ char str[]=%c%s%c;printf(str,34,str,34);}";
printf(str,34,str,34);
}

OutPut:
main(){ char str[]="main(){ char str[]=%c%s%c;printf(str,34,str,34);}";printf(str,34,str,34);}

Explaination: As we have seen above, it should be devided into two parts like code and data. So here value of the character array str is data which is placed between the double quotes. And remaining is code. For displaying that data, we need to use printf() function.Here comes the trick, for displaying double quotes("), we used equivalent ASCII value 34. and we are done. So for printf, first str from left is replaced with data, 34 is for quotes, another str is for variable and 34 for quotes. Final printf internally looks like below.
printf("main(){ char str[]=%c%s%c",34,str,34);
Here the output displayed in one single line. If you want next line, just add '%c'  to the string data and ASCII value of the new line (10) to the printf() function. Below is the C Program for that.

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

Output:
#include<stdio.h>
main()
{
char str[]="#include<stdio.h<%cmain()%c{ %cchar str[]=%c%s%c;%cprintf(str,10,10,10,34,str,34,10,10,10);%c}%c";
printf(str,10,10,10,34,str,34,10,10,10);
}

How to test it: How to know that, whether your program is generating exact source code or not.Just execute it and get the output in new C file. Compile that C file, if it executes successfully, your program is working and generating source code of the program itself.

No comments:

Popular Posts