My first quine in C

3 minute read

According to Wikipedia, Quine is defined as a “non-empty computer program which takes no input and produces a copy of its own source code as its only output.”. Sounds simple enough so I decided to take the challenge and build my own quine in C that is written with code formatting in consideration and yields no Compiler warning . My first few trails weren’t something useful at all. Here is example of What I tried at the very beginning:

#include <stdio.h> 
int main(void)
{
	 printf("#include <stdio.h>\nint main(void)\n{\n\tprintf(\"#include ... oh no I am repeating over and over\")");
}

So it became clear that it is not going to work this way, and I’m doing something wrong. The problem is that there would be a piece of code that is written to print the piece of code before it and to print it we need extra code which in turn is not printed and needs extra code to be printed and so on… Actually I made some research and after “Googling” for a while I found out what was wrong. The idea is to have a string that contains all the program code (except itself) and another string to contain that string. It is kind of confusing

#include <stdio.h>
int main(void) {
	const char *s1 = "#include <stdio.h>\nint main(void) {\n\t%s\n\tconst char *s2 = \"%s\"\n\tprintf(s1, s2, s3);\n}";
	const char *s2 = "const char *s1 = \"#include <stdio.h>\nint main(void) {\n\t%s\n\tprintf(s1, s2, s3);\n\";";
	printf(s1, s2, s2);
}

As you may have noticed, I exploited the idea that printf will always execute the format specifier in the first string while the others are printed but as you may have noticed this is not a quine and some characters are not printed exactly (like the “(") and the newline (\n) and the tab (\t) so we have to use a trick to remove these characters and substitute them with their numerical ASCII representation this way we can escape from the problem of back-slashing with out getting into troubles. But another problem arised from not executing the format specifiers on the s2 character array (I cant put any %c because it wont be executed.) so each of s1 and S2 should have its own printf command. the final version of this code is :


#include <stdio.h> /*Created By Ahmed Mohamed Abd El Mawgood */
int main(void)    /*Email: ahmedsoliman0x666@gmail.com*/
{
	const char *t1="#include <stdio.h> /*Created By Ahmed Mohamed Abd El Mawgood*/%cint main(void)    /*Email: ahmedsoliman0x666@gmail.com*/%c{%c%c";
	const char *t2="const char *t1 = %c%s%c;%c%cconst char *t2 = %c%s%c;%c%cchar n=10, q=58,t=9;%c%cprintf(t1,n,n,n,t);%c%cprintf(t2,q,t1,q,n,t,q,t2,q,n,t,n,t,n,t,n,n);%c}%c";
	char n=10, q=34,t=9;
	printf(t1,n,n,n,t);
	printf(t2,q,t1,q,n,t,q,t2,q,n,t,n,t,n,t,n,n);
}

Updated:

Leave a Comment