write a c program which produces its own source code as its output






How do you write a program which produces its own source code as its output in c language?

#include<stdio.h>

int main(){
    FILE *fp;
    char c;

    fp = fopen(__FILE__,"r");
 
    do{
         c= getc(fp);
         putchar(c);
    }
    while(c!=EOF);

    fclose(fp);
   
    return 0;
}

Output:
#include<stdio.h>

int main(){
    FILE *fp;
    char c;

    fp = fopen(__FILE__,"r");
 
    do{
         c= getc(fp);
         putchar(c);
    }
    while(c!=EOF);

    fclose(fp);
   
    return 0;
}










1. Write a c program to convert decimal number to hexadecimal number.
3. Write a c program to convert octal number to decimal number.
4. Write a c program to convert octal number to hexadecimal number.
5. Write a c program to convert hexadecimal number to decimal number.
6. Write a c program to convert hexadecimal number to octal number.
8. Write a c program to convert binary number to hexadecimal number.
9. Write a c program to convert binary number to octal number.
11. Write a c program to convert hexadecimal number to binary number.
12. Write a c program to convert octal number to binary number.
14. Write a c program to convert centigrade to fahrenheit.

11 comments:

Unknown said...

can sm1 explain it

Anonymous said...

The __FILE__ macro expands to full path of the current input file.
So, in the program __FILE__ is replaced by the path of the program.
Then we simply read from the file and display it.

Anonymous said...

thnx....:):):)


excellent answer...:)

Anonymous said...

Thanks a lot ....

Anonymous said...

very good answer

Vijay NV said...

the above wont run if the source file is deleted.. but this will

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

Anonymous said...

very nice

Mohammed Shafeeque said...

wonderful idea..

Unknown said...

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

Hey Boddy Can you explain the line?
How it works?
Advance Thank you.

Deep said...

plz explain this code

Gary Forbis said...

OK, maybe those who care figured it out. Here is the explanation:
printf is print formatted. It uses the string specified by the first parameter and applies the rest of the arguments based upon the formatting characters. In this case %s means string, %c means character.
34 is the ascii character ".
%c%s%c puts the string p inside quotes.