0

I came across this a few days ago.what i want to know is how to print the content of a C program as its output.consider the following small c code snipet:

#include<stdio.h>
#include<conio.h>
void main()
{
int a;
int b;
int sum;
}

how to modify the above code so that on executing it displays the same content of the code: the output should be:

#include<stdio.h>
#include<conio.h>
void main()
{
int a;
int b;
int sum;
}

I hope my question is not doubtful.

R R
  • 2,999
  • 2
  • 24
  • 42

3 Answers3

2
#include <stdio.h>
const char*s="#include <stdio.h>%cconst char*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);}
Jonathan Leffler
  • 730,956
  • 141
  • 904
  • 1,278
2

Here's how I would do it:

#include <stdio.h>
#include <stdlib.h>

int main(void)
{
    FILE *f = fopen(__FILE__, "r");
    if (!f)
        exit(-1);

    fseek(f, 0, SEEK_END);
    long n = ftell(f);
    fseek(f, 0, SEEK_SET);

    char *buf = malloc(n + 1);
    if (!buf)
        exit(-1);

    if (fread(buf, n, 1, f) < 1)
        exit(-1);

    buf[n] = 0;
    puts(buf);

    free(buf);
    fclose(f);
    return 0;
}
0

The code you wrote will never compile to a program that produces that same code as its output: this should be clear, because that code doesn't print anything at all! So it definitely won't print the whole C file you want.

You are looking for this:

http://en.wikipedia.org/wiki/Quine_%28computing%29

Andrey Mishchenko
  • 3,986
  • 2
  • 19
  • 37