I first read about quines several years ago but have never gotten around to trying to write one. I decided to write it in my language of choice, C/C++, and more specifically C to keep it as simple as possible. The code could be shorter - I've seen one liner Quines written in C - but I wanted to keep proper formatting and commenting and to have this formatting persist in the result of running it.
#include <cstdio>
// C-Quine
int main() {
char *s = "#include <cstdio>%c// C-Quine%cint main() {%c char *s = %c%s%c;%c printf(s, 0x0a, 0x0a, 0x0a, 0x22, s, 0x22, 0x0a, 0x0a, 0x0a);%c return 0;%c}";
printf(s, 0x0a, 0x0a, 0x0a, 0x22, s, 0x22, 0x0a, 0x0a, 0x0a);
return 0;
}
To run, compile Quine.cpp into a binary Quine.
Then run the binary and redirect its output back into the original source file to overwrite its contents.
$ gcc Quine.c -o Quine; ./Quine > Quine.c
If everything has worked the source file should remain unchanged. Run the Quine repeatedly to circularly regenerate the source file.